home *** CD-ROM | disk | FTP | other *** search
/ Nautilus 1992 July / Nautilus-3-8 / Nautilus-3-8.bin / Tools & Utilities / Techy Stuff / Development Environments ƒ / Perl 4.0.2 ƒ / PerlHelp < prev    next >
Encoding:
Text File  |  1992-01-20  |  219.3 KB  |  5,786 lines

  1. ╛KY CopyrightNotice
  2. ╛C  Larry Wall <lwall@netlabs.com>
  3. Macintosh port by 
  4.  
  5.    Matthias Neeracher <neeri@iis.ethz.ch>
  6.    Tim Endres         <time@ice.com>
  7.  
  8. ╛KY Help
  9. PerlHelp
  10. ╛KL About╔Perl
  11. Perl╔Options
  12. Perl╔Types
  13. Perl╔Syntax
  14. Perl╔Compound╔Statements
  15. Perl╔Simple╔Statements
  16. Perl╔Expressions
  17. Perl╔Operators
  18. Perl╔Precedence
  19. Perl╔Subroutines
  20. Perl╔Regexp
  21. Perl╔Formats
  22. Perl╔IPC
  23. Perl╔Variables
  24. Perl╔Packages
  25. Perl╔Style
  26. Perl╔Debugging
  27. Perl╔Environment
  28. Perl╔Diagnostics
  29. Perl╔Traps
  30. Perl╔Errata
  31. Perl╔Bugs
  32. Perl╔Macintosh╔Extensions
  33.  
  34. accept
  35. alarm
  36. atan2
  37. bind
  38. binmode
  39. caller
  40. chdir
  41. chmod
  42. chop
  43. chown
  44. chroot
  45. close
  46. closedir
  47. connect
  48. cos
  49. crypt
  50. dbmclose
  51. dbmopen
  52. defined
  53. delete
  54. die
  55. do
  56. dump
  57. each
  58. eof
  59. eval
  60. exec
  61. exit
  62. exp
  63. fcntl
  64. fileno
  65. flock
  66. fork
  67. getc
  68. getlogin
  69. getpeername
  70. getpgrp
  71. getppid
  72. getpriority
  73. getpwnam
  74. getsockname
  75. getsockopt
  76. gmtime
  77. goto
  78. grep
  79. hex
  80. index
  81. int
  82. ioctl
  83. join
  84. keys
  85. kill
  86. last
  87. length
  88. link
  89. listen
  90. local
  91. localtime
  92. log
  93. lstat
  94. m
  95. mkdir
  96. msgctl
  97. msgget
  98. msgsnd
  99. msgrcv
  100. next
  101. oct
  102. open
  103. opendir
  104. ord
  105. pack
  106. pipe
  107. pop
  108. print
  109. printf
  110. push
  111. q
  112. rand
  113. read
  114. readdir
  115. readlink
  116. recv
  117. redo
  118. rename
  119. require
  120. reset
  121. return
  122. reverse
  123. rewinddir
  124. rindex
  125. rmdir
  126. s
  127. scalar
  128. seek
  129. seekdir
  130. select
  131. semctl
  132. semget
  133. semop
  134. send
  135. setpgrp
  136. setpriority
  137. setsockopt
  138. shift
  139. shmctl
  140. shmget
  141. shmread
  142. shutdown
  143. sin
  144. sleep
  145. socket
  146. socketpair
  147. sort
  148. splice
  149. split
  150. sprintf
  151. sqrt
  152. srand
  153. stat
  154. study
  155. substr
  156. symlink
  157. syscall
  158. sysread
  159. system
  160. syswrite
  161. tell
  162. telldir
  163. time
  164. times
  165. tr
  166. truncate
  167. umask
  168. undef
  169. unlink
  170. unpack
  171. unshift
  172. utime
  173. values
  174. vec
  175. wait
  176. waitpid
  177. wantarray
  178. warn
  179. write
  180. ╛KY Perl
  181. About╔Perl
  182. ╛C
  183. Perl -- Practical Extraction and Report Language
  184.  
  185. Perl is an interpreted language optimized for scanning arbitrary
  186. text files, extracting information from those text files, and
  187. printing reports based on that information. It's also a good
  188. language for many system management tasks. The language is intended
  189. to be practical (easy to use, efficient, complete) rather than
  190. beautiful (tiny, elegant, minimal).  It combines (in the author's
  191. opinion, anyway) some of the best features of C, sed, awk, and sh,
  192. so people familiar with those languages should have little
  193. difficulty with it.  (Language historians will also note some
  194. vestiges of csh, Pascal, and even BASIC-PLUS.) Expression syntax
  195. corresponds quite closely to C expression syntax. Unlike most Unix
  196. utilities, perl does not arbitrarily limit the size of your data--if
  197. you've got the memory, perl can slurp in your whole file as a single
  198. string. Recursion is of unlimited depth.  And the hash tables used by
  199. associative arrays grow as necessary to prevent degraded performance.
  200. Perl uses sophisti- cated pattern matching techniques to scan large
  201. amounts of data very quickly. Although optimized for scanning text,
  202. perl can also deal with binary data, and can make dbm files look like
  203. associative arrays (where dbm is available). Setuid perl scripts are
  204. safer than C programs through a dataflow tracing mechanism which
  205. prevents many stupid security holes.  If you have a problem that
  206. would ordinarily use sed or awk or sh, but it exceeds their
  207. capabilities or must run a little faster, and you don't want to write
  208. the silly thing in C, then perl may be for you.  There are also
  209. translators to turn your sed and awk scripts into perl scripts.
  210. OK, enough hype.
  211.  
  212. Upon startup, perl looks for your script in one of the following
  213. places:
  214.  
  215. 1.  Specified line by line via -e switches on the command line.
  216.  
  217. 2.  Contained in the file specified by the first filename on the
  218.     command line.  (Note that systems supporting the #! notation
  219.     invoke interpreters this way.)
  220.  
  221. 3.  Passed in implicitly via standard input.  This only works if
  222.     there are no filename arguments--to pass arguments to a stdin
  223.     script you must explicitly specify a - for the script name.
  224.  
  225. After locating your script, perl compiles it to an internal form.
  226. If the script is syntactically correct, it is executed.
  227.  
  228. ╛KY Perl╔Options
  229. ╛C A single-character option may be combined with the following
  230. option, if any.  This is particularly useful when invoking a
  231. script using the #! construct which only allows one argument.
  232. Example:
  233.  
  234.      #!/usr/bin/perl -spi.bak # same as -s -p -i.bak
  235.      ...
  236.  
  237. Options include:
  238.  
  239. -0digits
  240.      specifies the record separator ($/) as an octal number.  If
  241.      there are no digits, the null character is the separator.
  242.      Other switches may precede or follow the digits.  For exam-
  243.      ple, if you have a version of find which can print filenames
  244.      terminated by the null character, you can say this:
  245.  
  246.                find . -name '*.bak' -print0 | perl -n0e unlink
  247.  
  248.      The special value 00 will cause Perl to slurp files in para-
  249.      graph mode.  The value 0777 will cause Perl to slurp files
  250.      whole since there is no legal character with that value.
  251.  
  252. -a   turns on autosplit mode when used with a -n or -p.  An
  253.      implicit split command to the @F array is done as the first
  254.      thing inside the implicit while loop produced by the -n or -p.
  255.  
  256.                     perl -ane 'print pop(@F), "\n";'
  257.  
  258.      is equivalent to
  259.  
  260.                     while (<>) {
  261.                          @F = split(' ');
  262.                          print pop(@F), "\n";
  263.                     }
  264.  
  265.  
  266. -c   causes perl to check the syntax of the script and then exit
  267.      without executing it.
  268.  
  269. -d   runs the script under the perl debugger.  See the section on
  270.      Debugging.
  271.  
  272. -Dnumber
  273.      sets debugging flags.  To watch how it executes your script,
  274.      use -D14.  (This only works if debugging is compiled into
  275.      your perl.) Another nice value is -D1024, which lists your
  276.      compiled syntax tree.  And -D512 displays compiled regular
  277.      expressions.
  278.  
  279. -e commandline
  280.      may be used to enter one line of script.  Multiple -e com-
  281.      mands may be given to build up a multi-line script.  If -e
  282.      is given, perl will not look for a script filename in the
  283.      argument list.
  284.  
  285. -iextension
  286.      specifies that files processed by the <> construct are to be
  287.      edited in-place.  It does this by renaming the input file,
  288.      opening the output file by the same name, and selecting that
  289.      output file as the default for print statements.  The exten-
  290.      sion, if supplied, is added to the name of the old file to
  291.      make a backup copy.  If no extension is supplied, no backup
  292.      is made.  Saying "perl -p -i.bak -e "s/foo/bar/;" ... " is
  293.      the same as using the script:
  294.  
  295.                     #!/usr/bin/perl -pi.bak
  296.                     s/foo/bar/;
  297.  
  298.      which is equivalent to
  299.  
  300.                     #!/usr/bin/perl
  301.                     while (<>) {
  302.                          if ($ARGV ne $oldargv) {
  303.                               rename($ARGV, $ARGV . '.bak');
  304.                               open(ARGVOUT, ">$ARGV");
  305.                               select(ARGVOUT);
  306.                               $oldargv = $ARGV;
  307.                          }
  308.                          s/foo/bar/;
  309.                     }
  310.                     continue {
  311.                      print;     # this prints to original filename
  312.                     }
  313.                     select(STDOUT);
  314.  
  315.      except that the -i form doesn't need to compare $ARGV to
  316.      $oldargv to know when the filename has changed.  It does,
  317.      however, use ARGVOUT for the selected filehandle.  Note that
  318.      STDOUT is restored as the default output filehandle after
  319.      the loop.
  320.  
  321.      You can use eof to locate the end of each input file, in
  322.      case you want to append to each file, or reset line number-
  323.      ing (see example under eof).
  324.  
  325. -Idirectory
  326.      may be used in conjunction with -P to tell the C preproces-
  327.      sor where to look for include files.  By default
  328.      /usr/include and /usr/lib/perl are searched.
  329.  
  330. -loctnum
  331.      enables automatic line-ending processing.  It has two
  332.      effects: first, it automatically chops the line terminator
  333.      when used with -n or -p , and second, it assigns $\ to have
  334.      the value of octnum so that any print statements will have
  335.      that line terminator added back on.  If octnum is omitted,
  336.      sets $\ to the current value of $/.  For instance, to trim
  337.      lines to 80 columns:
  338.  
  339.                     perl -lpe 'substr($_, 80) = ""'
  340.  
  341.      Note that the assignment $\ = $/ is done when the switch is
  342.      processed, so the input record separator can be different
  343.      than the output record separator if the -l switch is fol-
  344.      lowed by a -0 switch:
  345.  
  346.                     gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
  347.  
  348.      This sets $\ to newline and then sets $/ to the null charac-
  349.      ter.
  350.  
  351. -n   causes perl to assume the following loop around your script,
  352.      which makes it iterate over filename arguments somewhat like
  353.      "sed -n" or awk:
  354.  
  355.                     while (<>) {
  356.                          ...       # your script goes here
  357.                     }
  358.  
  359.      Note that the lines are not printed by default.  See -p to
  360.      have lines printed.  Here is an efficient way to delete all
  361.      files older than a week:
  362.  
  363.                     find . -mtime +7 -print | perl -nle 'unlink;'
  364.  
  365.      This is faster than using the -exec switch of find because
  366.      you don't have to start a process on every filename found.
  367.  
  368. -p   causes perl to assume the following loop around your script,
  369.      which makes it iterate over filename arguments somewhat like
  370.      sed:
  371.  
  372.                     while (<>) {
  373.                          ...       # your script goes here
  374.                     } continue {
  375.                          print;
  376.                     }
  377.  
  378.      Note that the lines are printed automatically.  To suppress
  379.      printing use the -n switch.  A -p overrides a -n switch.
  380.  
  381. -P   causes your script to be run through the C preprocessor
  382.      before compilation by perl.  (Since both comments and cpp
  383.      directives begin with the # character, you should avoid
  384.      starting comments with any words recognized by the C prepro-
  385.      cessor such as "if", "else" or "define".)
  386.  
  387. -s   enables some rudimentary switch parsing for switches on the
  388.      command line after the script name but before any filename
  389.      arguments (or before a --).  Any switch found there is
  390.      removed from @ARGV and sets the corresponding variable in
  391.      the perl script.  The following script prints "true" if and
  392.      only if the script is invoked with a -xyz switch.
  393.  
  394.                     #!/usr/bin/perl -s
  395.                     if ($xyz) { print "true\n"; }
  396.  
  397.  
  398. -S   makes perl use the PATH environment variable to search for
  399.      the script (unless the name of the script starts with a
  400.      slash).  Typically this is used to emulate #! startup on
  401.      machines that don't support #!, in the following manner:
  402.  
  403.                     #!/usr/bin/perl
  404.                     eval "exec /usr/bin/perl -S $0 $*"
  405.                          if $running_under_some_shell;
  406.  
  407.      The system ignores the first line and feeds the script to
  408.      /bin/sh, which proceeds to try to execute the perl script as
  409.      a shell script.  The shell executes the second line as a
  410.      normal shell command, and thus starts up the perl inter-
  411.      preter.  On some systems $0 doesn't always contain the full
  412.      pathname, so the -S tells perl to search for the script if
  413.      necessary.  After perl locates the script, it parses the
  414.      lines and ignores them because the variable
  415.      $running_under_some_shell is never true.  A better construct
  416.      than $* would be ${1+"$@"}, which handles embedded spaces
  417.      and such in the filenames, but doesn't work if the script is
  418.      being interpreted by csh.  In order to start up sh rather
  419.      than csh, some systems may have to replace the #! line with
  420.      a line containing just a colon, which will be politely
  421.      ignored by perl.  Other systems can't control that, and need
  422.      a totally devious construct that will work under any of csh,
  423.      sh or perl, such as the following:
  424.  
  425.                     eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
  426.                     & eval 'exec /usr/bin/perl -S $0 $argv:q'
  427.                          if 0;
  428.  
  429.  
  430. -u   causes perl to dump core after compiling your script.  You
  431.      can then take this core dump and turn it into an executable
  432.      file by using the undump program (not supplied).  This
  433.      speeds startup at the expense of some disk space (which you
  434.      can minimize by stripping the executable).  (Still, a "hello
  435.      world" executable comes out to about 200K on my machine.) If
  436.      you are going to run your executable as a set-id program
  437.      then you should probably compile it using taintperl rather
  438.      than normal perl.  If you want to execute a portion of your
  439.      script before dumping, use the dump operator instead.  Note:
  440.      availability of undump is platform specific and may not be
  441.      available for a specific port of perl.
  442.  
  443. -U   allows perl to do unsafe operations.  Currently the only
  444.      "unsafe" operation is the unlinking of directories while
  445.      running as superuser.
  446.  
  447. -v   prints the version and patchlevel of your perl executable.
  448.  
  449. -w   prints warnings about identifiers that are mentioned only
  450.      once, and scalar variables that are used before being set.
  451.      Also warns about redefined subroutines, and references to
  452.      undefined filehandles or filehandles opened readonly that
  453.      you are attempting to write on.  Also warns you if you use
  454.      == on values that don't look like numbers, and if your sub-
  455.      routines recurse more than 100 deep.
  456.  
  457. -xdirectory
  458.      tells perl that the script is embedded in a message.  Lead-
  459.      ing garbage will be discarded until the first line that
  460.      starts with #! and contains the string "perl".  Any meaning-
  461.      ful switches on that line will be applied (but only one
  462.      group of switches, as with normal #! processing).  If a
  463.      directory name is specified, Perl will switch to that direc-
  464.      tory before running the script.  The -x switch only controls
  465.      the the disposal of leading garbage.  The script must be
  466.      terminated with __END__ if there is trailing garbage to be
  467.      ignored (the script can process any or all of the trailing
  468.      garbage via the DATA filehandle if desired).
  469. ╛KY Perl╔Types
  470. ╛C Perl has three data types: scalars, arrays of scalars, and asso-
  471. ciative arrays of scalars.  Normal arrays are indexed by number,
  472. and associative arrays by string.
  473.  
  474. The interpretation of operations and values in perl sometimes
  475. depends on the requirements of the context around the operation
  476. or value.  There are three major contexts: string, numeric and
  477. array.  Certain operations return array values in contexts want-
  478. ing an array, and scalar values otherwise.  (If this is true of
  479. an operation it will be mentioned in the documentation for that
  480. operation.) Operations which return scalars don't care whether
  481. the context is looking for a string or a number, but scalar vari-
  482. ables and values are interpreted as strings or numbers as
  483. appropriate to the context.  A scalar is interpreted as TRUE in
  484. the boolean sense if it is not the null string or 0.  Booleans
  485. returned by operators are 1 for true and 0 or '' (the null
  486. string) for false.
  487.  
  488. There are actually two varieties of null string: defined and
  489. undefined.  Undefined null strings are returned when there is no
  490. real value for something, such as when there was an error, or at
  491. end of file, or when you refer to an uninitialized variable or
  492. element of an array.  An undefined null string may become defined
  493. the first time you access it, but prior to that you can use the
  494. defined() operator to determine whether the value is defined or
  495. not.
  496.  
  497. References to scalar variables always begin with '$', even when
  498. referring to a scalar that is part of an array.  Thus:
  499.  
  500.           $days           # a simple scalar variable
  501.           $days[28]       # 29th element of array @days
  502.           $days{'Feb'}    # one value from an associative array
  503.           $#days          # last index of array @days
  504.  
  505. but entire arrays or array slices are denoted by '@':
  506.  
  507.           @days           # ($days[0], $days[1],... $days[n])
  508.           @days[3,4,5]    # same as @days[3..5]
  509.           @days{'a','c'}  # same as ($days{'a'},$days{'c'})
  510.  
  511. and entire associative arrays are denoted by '%':
  512.  
  513.           %days           # (key1, val1, key2, val2 ...)
  514.  
  515. Any of these eight constructs may serve as an lvalue, that is,
  516. may be assigned to.  (It also turns out that an assignment is
  517. itself an lvalue in certain contexts--see examples under s, tr
  518. and chop.) Assignment to a scalar evaluates the righthand side in
  519. a scalar context, while assignment to an array or array slice
  520. evaluates the righthand side in an array context.
  521.  
  522. You may find the length of array @days by evaluating "$#days", as
  523. in csh.  (Actually, it's not the length of the array, it's the
  524. subscript of the last element, since there is (ordinarily) a 0th
  525. element.) Assigning to $#days changes the length of the array.
  526. Shortening an array by this method does not actually destroy any
  527. values.  Lengthening an array that was previously shortened
  528. recovers the values that were in those elements.  You can also
  529. gain some measure of efficiency by preextending an array that is
  530. going to get big.  (You can also extend an array by assigning to
  531. an element that is off the end of the array.  This differs from
  532. assigning to $#whatever in that intervening values are set to
  533. null rather than recovered.) You can truncate an array down to
  534. nothing by assigning the null list () to it.  The following are
  535. exactly equivalent
  536.  
  537.      @whatever = ();
  538.      $#whatever = $[ - 1;
  539.  
  540.  
  541. If you evaluate an array in a scalar context, it returns the
  542. length of the array.  The following is always true:
  543.  
  544.      scalar(@whatever) == $#whatever - $[ + 1;
  545.  
  546. If you evaluate an associative array in a scalar context, it returns
  547. a value which is true if and only if the array contains any elements.
  548. (If there are any elements, the value returned is a string consisting
  549. of the number of used buckets and the number of allocated buckets, 
  550. separated by a slash.)
  551.  
  552. Multi-dimensional arrays are not directly supported, but see the
  553. discussion of the $; variable later for a means of emulating mul-
  554. tiple subscripts with an associative array.  You could also write
  555. a subroutine to turn multiple subscripts into a single subscript.
  556.  
  557. Every data type has its own namespace.  You can, without fear of
  558. conflict, use the same name for a scalar variable, an array, an
  559. associative array, a filehandle, a subroutine name, and/or a
  560. label.  Since variable and array references always start with
  561. '$', '@', or '%', the "reserved" words aren't in fact reserved
  562. with respect to variable names.  (They ARE reserved with respect
  563. to labels and filehandles, however, which don't have an initial
  564. special character.  Hint: you could say open(LOG,'logfile')
  565. rather than open(log,'logfile').  Using uppercase filehandles
  566. also improves readability and protects you from conflict with
  567. future reserved words.) Case IS significant--"FOO", "Foo" and
  568. "foo" are all different names.  Names which start with a letter
  569. may also contain digits and underscores.  Names which do not
  570. start with a letter are limited to one character, e.g. "$%" or
  571. "$$".  (Most of the one character names have a predefined signi-
  572. ficance to perl.  More later.)
  573.  
  574. Numeric literals are specified in any of the usual floating point
  575. or integer formats:
  576.  
  577.           12345
  578.           12345.67
  579.           .23E-10
  580.           0xffff     # hex
  581.           0377  # octal
  582.  
  583. String literals are delimited by either single or double quotes.
  584. They work much like shell quotes: double-quoted string literals
  585. are subject to backslash and variable substitution; single-quoted
  586. strings are not (except for \' and \\).  The usual backslash
  587. rules apply for making characters such as newline, tab, etc., as
  588. well as some more exotic forms:
  589.  
  590.      \t        tab
  591.      \n        newline
  592.      \r        return
  593.      \f        form feed
  594.      \b        backspace
  595.      \a        alarm (bell)
  596.      \e        escape
  597.      \033      octal char
  598.      \x1b      hex char
  599.      \c[       control char
  600.      \l        lowercase next char
  601.      \u        uppercase next char
  602.      \L        lowercase till \E
  603.      \U        uppercase till \E
  604.      \E        end case modification
  605.  
  606. You can also embed newlines directly in your strings, i.e. they
  607. can end on a different line than they begin.  This is nice, but
  608. if you forget your trailing quote, the error will not be reported
  609. until perl finds another line containing the quote character,
  610. which may be much further on in the script.  Variable substitu-
  611. tion inside strings is limited to scalar variables, normal array
  612. values, and array slices.  (In other words, identifiers beginning
  613. with $ or @, followed by an optional bracketed expression as a
  614. subscript.) The following code segment prints out "The price is
  615. $100."
  616.  
  617.           $Price = '$100';               # not interpreted
  618.           print "The price is $Price.\n";# interpreted
  619.  
  620. Note that you can put curly brackets around the identifier to
  621. delimit it from following alphanumerics.  Also note that a single
  622. quoted string must be separated from a preceding word by a space,
  623. since single quote is a valid character in an identifier (see
  624. Packages).
  625.  
  626. Two special literals are __LINE__ and __FILE__, which represent
  627. the current line number and filename at that point in your pro-
  628. gram.  They may only be used as separate tokens; they will not be
  629. interpolated into strings.  In addition, the token __END__ may be
  630. used to indicate the logical end of the script before the actual
  631. end of file.  Any following text is ignored (but may be read via
  632. the DATA filehandle).  The two control characters ^D and ^Z are
  633. synonyms for __END__.
  634.  
  635. A word that doesn't have any other interpretation in the grammar
  636. will be treated as if it had single quotes around it.  For this
  637. purpose, a word consists only of alphanumeric characters and
  638. underline, and must start with an alphabetic character.  As with
  639. filehandles and labels, a bare word that consists entirely of
  640. lowercase letters risks conflict with future reserved words, and
  641. if you use the -w switch, Perl will warn you about any such
  642. words.
  643.  
  644. Array values are interpolated into double-quoted strings by join-
  645. ing all the elements of the array with the delimiter specified in
  646. the $" variable, space by default.  (Since in versions of perl
  647. prior to 3.0 the @ character was not a metacharacter in double-
  648. quoted strings, the interpolation of @array, $array[EXPR],
  649. @array[LIST], $array{EXPR}, or @array{LIST} only happens if array
  650. is referenced elsewhere in the program or is predefined.) The
  651. following are equivalent:
  652.  
  653.      $temp = join($",@ARGV);
  654.      system "echo $temp";
  655.  
  656.      system "echo @ARGV";
  657.  
  658.  
  659. Within search patterns (which also undergo double-quotish substi-
  660. tution) there is a bad ambiguity:  Is /$foo[bar]/ to be inter-
  661. preted as /${foo}[bar]/ (where [bar] is a character class for the
  662. regular expression) or as /${foo[bar]}/ (where [bar] is the sub-
  663. script to array @foo)?  If @foo doesn't otherwise exist, then
  664. it's obviously a character class.  If @foo exists, perl takes a
  665. good guess about [bar], and is almost always right.  If it does
  666. guess wrong, or if you're just plain paranoid, you can force the
  667. correct interpretation with curly brackets as above.
  668.  
  669. A line-oriented form of quoting is based on the shell here-is
  670. syntax.  Following a << you specify a string to terminate the
  671. quoted material, and all lines following the current line down to
  672. the terminating string are the value of the item.  The terminat-
  673. ing string may be either an identifier (a word), or some quoted
  674. text.  If quoted, the type of quotes you use determines the
  675. treatment of the text, just as in regular quoting.  An unquoted
  676. identifier works like double quotes.  There must be no space
  677. between the << and the identifier.  (If you put a space it will
  678. be treated as a null identifier, which is valid, and matches the
  679. first blank line--see Merry Christmas example below.) The ter-
  680. minating string must appear by itself (unquoted and with no sur-
  681. rounding whitespace) on the terminating line.
  682.  
  683. print <<EOF;        # same as above
  684. The price is $Price.
  685. EOF
  686.  
  687. print <<"EOF";      # same as above
  688. The price is $Price.
  689. EOF
  690.  
  691. print << x 10;      # null identifier is delimiter
  692. Merry Christmas!
  693.  
  694. print <<`EOC`;      # execute commands
  695. echo hi there
  696. echo lo there
  697. EOC
  698.  
  699. print <<foo, <<bar; # you can stack them
  700. I said foo.
  701. foo
  702. I said bar.
  703. bar
  704.  
  705. Array literals are denoted by separating individual values by
  706. commas, and enclosing the list in parentheses:
  707.  
  708.      (LIST)
  709.  
  710. In a context not requiring an array value, the value of the array
  711. literal is the value of the final element, as in the C comma
  712. operator.  For example,
  713.  
  714.           @foo = ('cc', '-E', $bar);
  715.  
  716. assigns the entire array value to array foo, but
  717.  
  718.           $foo = ('cc', '-E', $bar);
  719.  
  720. assigns the value of variable bar to variable foo.  Note that the
  721. value of an actual array in a scalar context is the length of the
  722. array; the following assigns to $foo the value 3:
  723.  
  724.           @foo = ('cc', '-E', $bar);
  725.           $foo = @foo;         # $foo gets 3
  726.  
  727. You may have an optional comma before the closing parenthesis of
  728. an array literal, so that you can say:
  729.  
  730.      @foo = (
  731.      1,
  732.      2,
  733.      3,
  734.      );
  735.  
  736. When a LIST is evaluated, each element of the list is evaluated
  737. in an array context, and the resulting array value is interpo-
  738. lated into LIST just as if each individual element were a member
  739. of LIST.  Thus arrays lose their identity in a LIST--the list
  740.  
  741.      (@foo,@bar,&SomeSub)
  742.  
  743. contains all the elements of @foo followed by all the elements of
  744. @bar, followed by all the elements returned by the subroutine
  745. named SomeSub.
  746.  
  747. A list value may also be subscripted like a normal array.  Exam-
  748. ples:
  749.  
  750.      $time = (stat($file))[8];     # stat returns array value
  751.      $digit = ('a','b','c','d','e','f')[$digit-10];
  752.      return (pop(@foo),pop(@foo))[0];
  753.  
  754.  
  755. Array lists may be assigned to if and only if each element of the
  756. list is an lvalue:
  757.  
  758.           ($a, $b, $c) = (1, 2, 3);
  759.  
  760.           ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  761.  
  762. The final element may be an array or an associative array:
  763.  
  764.           ($a, $b, @rest) = split;
  765.           local($a, $b, %rest) = @_;
  766.  
  767.  
  768. You can actually put an array anywhere in the list, but the first
  769. array in the list will soak up all the values, and anything after
  770. it will get a null value.  This may be useful in a local().
  771.  
  772. An associative array literal contains pairs of values to be
  773. interpreted as a key and a value:
  774.  
  775.           # same as map assignment above
  776.           %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  777.  
  778. Array assignment in a scalar context returns the number of ele-
  779. ments produced by the expression on the right side of the assign-
  780. ment:
  781.  
  782.      $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
  783.  
  784.  
  785. There are several other pseudo-literals that you should know
  786. about.  If a string is enclosed by backticks (grave accents), it
  787. first undergoes variable substitution just like a double quoted
  788. string.  It is then interpreted as a command, and the output of
  789. that command is the value of the pseudo-literal, like in a shell.
  790. In a scalar context, a single string consisting of all the output
  791. is returned.  In an array context, an array of values is
  792. returned, one for each line of output.  (You can set $/ to use a
  793. different line terminator.) The command is executed each time the
  794. pseudo-literal is evaluated.  The status value of the command is
  795. returned in $? (see Predefined Names for the interpretation of
  796. $?).  Unlike in csh, no translation is done on the return data--
  797. newlines remain newlines.  Unlike in any of the shells, single
  798. quotes do not hide variable names in the command from interpreta-
  799. tion.  To pass a $ through to the shell you need to hide it with
  800. a backslash.
  801.  
  802. Evaluating a filehandle in angle brackets yields the next line
  803. from that file (newline included, so it's never false until EOF,
  804. at which time an undefined value is returned).  Ordinarily you
  805. must assign that value to a variable, but there is one situation
  806. where an automatic assignment happens.  If (and only if) the
  807. input symbol is the only thing inside the conditional of a while
  808. loop, the value is automatically assigned to the variable "$_".
  809. (This may seem like an odd thing to you, but you'll use the con-
  810. struct in almost every perl script you write.) Anyway, the fol-
  811. lowing lines are equivalent to each other:
  812.  
  813.           while ($_ = <STDIN>) { print; }
  814.           while (<STDIN>) { print; }
  815.           for (;<STDIN>;) { print; }
  816.           print while $_ = <STDIN>;
  817.           print while <STDIN>;
  818.  
  819. The filehandles STDIN, STDOUT and STDERR are predefined.  (The
  820. filehandles stdin, stdout and stderr will also work except in
  821. packages, where they would be interpreted as local identifiers
  822. rather than global.) Additional filehandles may be created with
  823. the open function.
  824.  
  825. If a <FILEHANDLE> is used in a context that is looking for an
  826. array, an array consisting of all the input lines is returned,
  827. one line per array element.  It's easy to make a LARGE data space
  828. this way, so use with care.
  829.  
  830. The null filehandle <> is special and can be used to emulate the
  831. behavior of sed and awk.  Input from <> comes either from stan-
  832. dard input, or from each file listed on the command line.  Here's
  833. how it works: the first time <> is evaluated, the ARGV array is
  834. checked, and if it is null, $ARGV[0] is set to '-', which when
  835. opened gives you standard input.  The ARGV array is then pro-
  836. cessed as a list of filenames.  The loop
  837.  
  838.      while (<>) {
  839.                     ...            # code for each line
  840.      }
  841.  
  842. is equivalent to
  843.  
  844.      unshift(@ARGV, '-') if $#ARGV < $[;
  845.      while ($ARGV = shift) {
  846.                     open(ARGV, $ARGV);
  847.                     while (<ARGV>) {
  848.                          ...       # code for each line
  849.                     }
  850.      }
  851.  
  852. except that it isn't as cumbersome to say.  It really does shift
  853. array ARGV and put the current filename into variable ARGV.  It
  854. also uses filehandle ARGV internally.  You can modify @ARGV
  855. before the first <> as long as you leave the first filename at
  856. the beginning of the array.  Line numbers ($.) continue as if the
  857. input was one big happy file.  (But see example under eof for how
  858. to reset line numbers on each file.)
  859.  
  860. If you want to set @ARGV to your own list of files, go right
  861. ahead.  If you want to pass switches into your script, you can
  862. put a loop on the front like this:
  863.  
  864.      while ($_ = $ARGV[0], /^-/) {
  865.                     shift;
  866.                last if /^--$/;
  867.                     /^-D(.*)/ && ($debug = $1);
  868.                     /^-v/ && $verbose++;
  869.                     ...       # other switches
  870.      }
  871.      while (<>) {
  872.                     ...       # code for each line
  873.      }
  874.  
  875.  
  876. The <> symbol will return FALSE only once.  If you call it again
  877. after this it will assume you are processing another @ARGV list,
  878. and if you haven't set @ARGV, will input from STDIN.
  879.  
  880. If the string inside the angle brackets is a reference to a
  881. scalar variable (e.g. <$foo>), then that variable contains the
  882. name of the filehandle to input from.
  883.  
  884. If the string inside angle brackets is not a filehandle, it is
  885. interpreted as a filename pattern to be globbed, and either an
  886. array of filenames or the next filename in the list is returned,
  887. depending on context.  One level of $ interpretation is done
  888. first, but you can't say <$foo> because that's an indirect
  889. filehandle as explained in the previous paragraph.  You could
  890. insert curly brackets to force interpretation as a filename glob:
  891. <${foo}>.  Example:
  892.  
  893.      while (<*.c>) {
  894.                     chmod 0644, $_;
  895.      }
  896.  
  897. is equivalent to
  898.  
  899.      open(foo, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  900.      while (<foo>) {
  901.                     chop;
  902.                     chmod 0644, $_;
  903.      }
  904.  
  905. In fact, it's currently implemented that way.  (Which means it
  906. will not work on filenames with spaces in them unless you have
  907. /bin/csh on your machine.) Of course, the shortest way to do the
  908. above is:
  909.  
  910.      chmod 0644, <*.c>;
  911.  
  912. ╛KY Perl╔Syntax
  913. ╛C A perl script consists of a sequence of declarations and com-
  914. mands.  The only things that need to be declared in perl are
  915. report formats and subroutines.  See the sections below for more
  916. information on those declarations.  All uninitialized user-
  917. created objects are assumed to start with a null or 0 value until
  918. they are defined by some explicit operation such as assignment.
  919. The sequence of commands is executed just once, unlike in sed and
  920. awk scripts, where the sequence of commands is executed for each
  921. input line.  While this means that you must explicitly loop over
  922. the lines of your input file (or files), it also means you have
  923. much more control over which files and which lines you look at.
  924. (Actually, I'm lying--it is possible to do an implicit loop with
  925. either the -n or -p switch.)
  926.  
  927. A declaration can be put anywhere a command can, but has no
  928. effect on the execution of the primary sequence of commands--
  929. declarations all take effect at compile time.  Typically all the
  930. declarations are put at the beginning or the end of the script.
  931.  
  932. Perl is, for the most part, a free-form language.  (The only
  933. exception to this is format declarations, for fairly obvious rea-
  934. sons.) Comments are indicated by the # character, and extend to
  935. the end of the line.  If you attempt to use /* */ C comments, it
  936. will be interpreted either as division or pattern matching,
  937. depending on the context.  So don't do that.
  938.  
  939. SEE ALSO
  940.  
  941. ╛KL Perl╔Compound╔Statements
  942. Perl╔Simple╔Statements
  943. Perl╔Expressions
  944. ╛KY Perl╔Compound╔Statements
  945. ╛C In perl, a sequence of commands may be treated as one command by
  946. enclosing it in curly brackets.  We will call this a BLOCK.
  947.  
  948. The following compound commands may be used to control flow:
  949.  
  950.      if (EXPR) BLOCK
  951.      if (EXPR) BLOCK else BLOCK
  952.      if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  953.      LABEL while (EXPR) BLOCK
  954.      LABEL while (EXPR) BLOCK continue BLOCK
  955.      LABEL for (EXPR; EXPR; EXPR) BLOCK
  956.      LABEL foreach VAR (ARRAY) BLOCK
  957.      LABEL BLOCK continue BLOCK
  958.  
  959. Note that, unlike C and Pascal, these are defined in terms of
  960. BLOCKs, not statements.  This means that the curly brackets are
  961. required--no dangling statements allowed.  If you want to write
  962. conditionals without curly brackets there are several other ways
  963. to do it.  The following all do the same thing:
  964.  
  965.      if (!open(foo)) { die "Can't open $foo: $!"; }
  966.      die "Can't open $foo: $!" unless open(foo);
  967.      open(foo) || die "Can't open $foo: $!"; # foo or bust!
  968.      open(foo) ? 'hi mom' : die "Can't open $foo: $!";
  969.                               # a bit exotic, that last one
  970.  
  971.  
  972. The if statement is straightforward.  Since BLOCKs are always
  973. bounded by curly brackets, there is never any ambiguity about
  974. which if an else goes with.  If you use unless in place of if,
  975. the sense of the test is reversed.
  976.  
  977. The while statement executes the block as long as the expression
  978. is true (does not evaluate to the null string or 0).  The LABEL
  979. is optional, and if present, consists of an identifier followed
  980. by a colon.  The LABEL identifies the loop for the loop control
  981. statements next, last, and redo (see below).  If there is a con-
  982. tinue BLOCK, it is always executed just before the conditional is
  983. about to be evaluated again, similarly to the third part of a for
  984. loop in C.  Thus it can be used to increment a loop variable,
  985. even when the loop has been continued via the next statement
  986. (similar to the C "continue" statement).
  987.  
  988. If the word while is replaced by the word until, the sense of the
  989. test is reversed, but the conditional is still tested before the
  990. first iteration.
  991.  
  992. In either the if or the while statement, you may replace "(EXPR)"
  993. with a BLOCK, and the conditional is true if the value of the
  994. last command in that block is true.
  995.  
  996. The for loop works exactly like the corresponding while loop:
  997.  
  998.      for ($i = 1; $i < 10; $i++) {
  999.                     ...
  1000.      }
  1001.  
  1002. is the same as
  1003.  
  1004.      $i = 1;
  1005.      while ($i < 10) {
  1006.                     ...
  1007.      } continue {
  1008.                     $i++;
  1009.      }
  1010.  
  1011. The foreach loop iterates over a normal array value and sets the
  1012. variable VAR to be each element of the array in turn.  The vari-
  1013. able is implicitly local to the loop, and regains its former
  1014. value upon exiting the loop.  The "foreach" keyword is actually
  1015. identical to the "for" keyword, so you can use "foreach" for rea-
  1016. dability or "for" for brevity.  If VAR is omitted, $_ is set to
  1017. each value.  If ARRAY is an actual array (as opposed to an
  1018. expression returning an array value), you can modify each element
  1019. of the array by modifying VAR inside the loop.  Examples:
  1020.  
  1021.      for (@ary) { s/foo/bar/; }
  1022.  
  1023.      foreach $elem (@elements) {
  1024.                     $elem *= 2;
  1025.      }
  1026.  
  1027.      for ((10,9,8,7,6,5,4,3,2,1,'BOOM')) {
  1028.                     print $_, "\n"; sleep(1);
  1029.      }
  1030.  
  1031.      for (1..15) { print "Merry Christmas\n"; }
  1032.  
  1033.      foreach $item (split(/:[\\\n:]*/, $ENV{'TERMCAP'})) {
  1034.                     print "Item: $item\n";
  1035.      }
  1036.  
  1037.  
  1038. The BLOCK by itself (labeled or not) is equivalent to a loop that
  1039. executes once.  Thus you can use any of the loop control state-
  1040. ments in it to leave or restart the block.  The continue block is
  1041. optional.  This construct is particularly nice for doing case
  1042. structures.
  1043.  
  1044.      foo: {
  1045.                     if (/^abc/) { $abc = 1; last foo; }
  1046.                     if (/^def/) { $def = 1; last foo; }
  1047.                     if (/^xyz/) { $xyz = 1; last foo; }
  1048.                     $nothing = 1;
  1049.      }
  1050.  
  1051. There is no official switch statement in perl, because there are
  1052. already several ways to write the equivalent.  In addition to the
  1053. above, you could write
  1054.  
  1055.      foo: {
  1056.                     $abc = 1, last foo  if /^abc/;
  1057.                     $def = 1, last foo  if /^def/;
  1058.                     $xyz = 1, last foo  if /^xyz/;
  1059.                     $nothing = 1;
  1060.      }
  1061.  
  1062. or
  1063.  
  1064.      foo: {
  1065.                     /^abc/ && do { $abc = 1; last foo; };
  1066.                     /^def/ && do { $def = 1; last foo; };
  1067.                     /^xyz/ && do { $xyz = 1; last foo; };
  1068.                     $nothing = 1;
  1069.      }
  1070.  
  1071. or
  1072.  
  1073.      foo: {
  1074.                     /^abc/ && ($abc = 1, last foo);
  1075.                     /^def/ && ($def = 1, last foo);
  1076.                     /^xyz/ && ($xyz = 1, last foo);
  1077.                     $nothing = 1;
  1078.      }
  1079.  
  1080. or even
  1081.  
  1082.      if (/^abc/)
  1083.                     { $abc = 1; }
  1084.      elsif (/^def/)
  1085.                     { $def = 1; }
  1086.      elsif (/^xyz/)
  1087.                     { $xyz = 1; }
  1088.      else
  1089.                     {$nothing = 1;}
  1090.  
  1091. As it happens, these are all optimized internally to a switch
  1092. structure, so perl jumps directly to the desired statement, and
  1093. you needn't worry about perl executing a lot of unnecessary
  1094. statements when you have a string of 50 elsifs, as long as you
  1095. are testing the same simple scalar variable using ==, eq, or pat-
  1096. tern matching as above.  (If you're curious as to whether the
  1097. optimizer has done this for a particular case statement, you can
  1098. use the -D1024 switch to list the syntax tree before execution.)
  1099.  
  1100. ╛KY Perl╔Simple╔Statements
  1101. ╛C The only kind of simple statement is an expression evaluated for
  1102. its side effects.  Every expression (simple statement) must be
  1103. terminated with a semicolon.  Note that this is like C, but
  1104. unlike Pascal (and awk).
  1105.  
  1106. Any simple statement may optionally be followed by a single
  1107. modifier, just before the terminating semicolon.  The possible
  1108. modifiers are:
  1109.  
  1110.      if EXPR
  1111.      unless EXPR
  1112.      while EXPR
  1113.      until EXPR
  1114.  
  1115. The if and unless modifiers have the expected semantics.  The
  1116. while and until modifiers also have the expected semantics (con-
  1117. ditional evaluated first), except when applied to a do-BLOCK or a
  1118. do-SUBROUTINE command, in which case the block executes once
  1119. before the conditional is evaluated.  This is so that you can
  1120. write loops like:
  1121.  
  1122.      do {
  1123.                     $_ = <STDIN>;
  1124.                     ...
  1125.      } until $_ eq ".\n";
  1126.  
  1127. (See the do operator below.  Note also that the loop control com-
  1128. mands described later will NOT work in this construct, since
  1129. modifiers don't take loop labels.  Sorry.)
  1130.  
  1131. ╛KY Perl╔Expressions
  1132. ╛C Since perl expressions work almost exactly like C expressions,
  1133. only the differences will be mentioned here.
  1134.  
  1135. Here's what perl has that C doesn't:
  1136.  
  1137. **      The exponentiation operator.
  1138.  
  1139. **=     The exponentiation assignment operator.
  1140.  
  1141. ()      The null list, used to initialize an array to null.
  1142.  
  1143. .       Concatenation of two strings.
  1144.  
  1145. .=      The concatenation assignment operator.
  1146.  
  1147. eq      String equality (== is numeric equality).  For a mnemonic
  1148.         just think of "eq" as a string.  (If you are used to the
  1149.         awk behavior of using == for either string or numeric
  1150.         equality based on the current form of the comparands,
  1151.         beware!  You must be explicit here.)
  1152.  
  1153. ne      String inequality (!= is numeric inequality).
  1154.  
  1155. lt      String less than.
  1156.  
  1157. gt      String greater than.
  1158.  
  1159. le      String less than or equal.
  1160.  
  1161. ge      String greater than or equal.
  1162.  
  1163. cmp     String comparison, returning -1, 0, or 1.
  1164.  
  1165. <=>     Numeric comparison, returning -1, 0, or 1.
  1166.  
  1167. =~      Certain operations search or modify the string "$_" by
  1168.         default.  This operator makes that kind of operation work
  1169.         on some other string.  The right argument is a search
  1170.         pattern, substitution, or translation.  The left argument
  1171.         is what is supposed to be searched, substituted, or
  1172.         translated instead of the default "$_".  The return value
  1173.         indicates the success of the operation.  (If the right
  1174.         argument is an expression other than a search pattern,
  1175.         substitution, or translation, it is interpreted as a
  1176.         search pattern at run time.  This is less efficient than
  1177.         an explicit search, since the pattern must be compiled
  1178.         every time the expression is evaluated.) The precedence
  1179.         of this operator is lower than unary minus and
  1180.         autoincrement/decrement, but higher than everything else.
  1181.  
  1182. !~      Just like =~ except the return value is negated.
  1183.  
  1184. x       The repetition operator.  Returns a string consisting of
  1185.         the left operand repeated the number of times specified
  1186.         by the right operand.  In an array context, if the left
  1187.         operand is a list in parens, it repeats the list.
  1188.  
  1189.              print '-' x 80;               # print row of dashes
  1190.              print '-' x80;                # illegal, x80 is identifier
  1191.  
  1192.              print "\t" x ($tab/8), ' ' x ($tab%8);  # tab over
  1193.  
  1194.              @ones = (1) x 80;               # an array of 80 1's
  1195.              @ones = (5) x @ones;          # set all elements to 5
  1196.  
  1197. x=      The repetition assignment operator.  Only works on
  1198.         scalars.
  1199.  
  1200. ..      The range operator, which is really two different opera-
  1201.         tors depending on the context.  In an array context,
  1202.         returns an array of values counting (by ones) from the
  1203.         left value to the right value.  This is useful for writ-
  1204.         ing "for (1..10)" loops and for doing slice operations on
  1205.         arrays.
  1206.  
  1207.         In a scalar context, .. returns a boolean value.  The
  1208.         operator is bistable, like a flip-flop..  Each .. opera-
  1209.         tor maintains its own boolean state.  It is false as long
  1210.         as its left operand is false.  Once the left operand is
  1211.         true, the range operator stays true until the right
  1212.         operand is true, AFTER which the range operator becomes
  1213.         false again.  (It doesn't become false till the next time
  1214.         the range operator is evaluated.  It can become false on
  1215.         the same evaluation it became true, but it still returns
  1216.         true once.) The right operand is not evaluated while the
  1217.         operator is in the "false" state, and the left operand is
  1218.         not evaluated while the operator is in the "true" state.
  1219.         The scalar .. operator is primarily intended for doing
  1220.         line number ranges after the fashion of sed or awk.  The
  1221.         precedence is a little lower than || and &&.  The value
  1222.         returned is either the null string for false, or a
  1223.         sequence number (beginning with 1) for true.  The
  1224.         sequence number is reset for each range encountered.  The
  1225.         final sequence number in a range has the string 'E0'
  1226.         appended to it, which doesn't affect its numeric value,
  1227.         but gives you something to search for if you want to
  1228.         exclude the endpoint.  You can exclude the beginning
  1229.         point by waiting for the sequence number to be greater
  1230.         than 1.  If either operand of scalar .. is static, that
  1231.         operand is implicitly compared to the $. variable, the
  1232.         current line number.  Examples:
  1233.  
  1234.         As a scalar operator:
  1235.              if (101 .. 200) { print; }     # print 2nd hundred lines
  1236.  
  1237.              next line if (1 .. /^$/); # skip header lines
  1238.  
  1239.              s/^/> / if (/^$/ .. eof());    # quote body
  1240.  
  1241.         As an array operator:
  1242.              for (101 .. 200) { print; }    # print $_ 100 times
  1243.  
  1244.              @foo = @foo[$[ .. $#foo]; # an expensive no-op
  1245.              @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
  1246.  
  1247. -x      A file test.  This unary operator takes one argument,
  1248.         either a filename or a filehandle, and tests the associ-
  1249.         ated file to see if something is true about it.  If the
  1250.         argument is omitted, tests $_, except for -t, which tests
  1251.         STDIN.  It returns 1 for true and '' for false, or the
  1252.         undefined value if the file doesn't exist.  Precedence is
  1253.         higher than logical and relational operators, but lower
  1254.         than arithmetic operators.  The operator may be any of:
  1255.              -r   File is readable by effective uid.
  1256.              -w   File is writable by effective uid.
  1257.              -x   File is executable by effective uid.
  1258.              -o   File is owned by effective uid.
  1259.              -R   File is readable by real uid.
  1260.              -W   File is writable by real uid.
  1261.              -X   File is executable by real uid.
  1262.              -O   File is owned by real uid.
  1263.              -e   File exists.
  1264.              -z   File has zero size.
  1265.              -s   File has non-zero size (returns size).
  1266.              -f   File is a plain file.
  1267.              -d   File is a directory.
  1268.              -l   File is a symbolic link.
  1269.              -p   File is a named pipe (FIFO).
  1270.              -S   File is a socket.
  1271.              -b   File is a block special file.
  1272.              -c   File is a character special file.
  1273.              -u   File has setuid bit set.
  1274.              -g   File has setgid bit set.
  1275.              -k   File has sticky bit set.
  1276.              -t   Filehandle is opened to a tty.
  1277.              -T   File is a text file.
  1278.              -B   File is a binary file (opposite of -T).
  1279.              -M   Age of file in days when script started.
  1280.              -A   Same for access time.
  1281.              -C   Same for inode change time.
  1282.  
  1283.         The interpretation of the file permission operators -r,
  1284.         -R, -w, -W, -x and -X is based solely on the mode of the
  1285.         file and the uids and gids of the user.  There may be
  1286.         other reasons you can't actually read, write or execute
  1287.         the file.  Also note that, for the superuser, -r, -R, -w
  1288.         and -W always return 1, and -x and -X return 1 if any
  1289.         execute bit is set in the mode.  Scripts run by the
  1290.         superuser may thus need to do a stat() in order to deter-
  1291.         mine the actual mode of the file, or temporarily set the
  1292.         uid to something else.
  1293.  
  1294.         Example:
  1295.              while (<>) {
  1296.                   chop;
  1297.                   next unless -f $_;  # ignore specials
  1298.                   ...
  1299.              }
  1300.  
  1301.         Note that -s/a/b/ does not do a negated substitution.
  1302.         Saying -exp($foo) still works as expected, however--only
  1303.         single letters following a minus are interpreted as file
  1304.         tests.
  1305.  
  1306.         The -T and -B switches work as follows.  The first block
  1307.         or so of the file is examined for odd characters such as
  1308.         strange control codes or metacharacters.  If too many odd
  1309.         characters (>10%) are found, it's a -B file, otherwise
  1310.         it's a -T file.  Also, any file containing null in the
  1311.         first block is considered a binary file.  If -T or -B is
  1312.         used on a filehandle, the current stdio buffer is exam-
  1313.         ined rather than the first block.  Both -T and -B return
  1314.         TRUE on a null file, or a file at EOF when testing a
  1315.         filehandle.
  1316.  
  1317. If any of the file tests (or either stat operator) are given the
  1318. special filehandle consisting of a solitary underline, then the
  1319. stat structure of the previous file test (or stat operator) is
  1320. used, saving a system call.  (This doesn't work with -t, and you
  1321. need to remember that lstat and -l will leave values in the stat
  1322. structure for the symbolic link, not the real file.) Example:
  1323.  
  1324.      print "Can do.\n" if -r $a || -w _ || -x _;
  1325.  
  1326.      stat($filename);
  1327.      print "Readable\n" if -r _;
  1328.      print "Writable\n" if -w _;
  1329.      print "Executable\n" if -x _;
  1330.      print "Setuid\n" if -u _;
  1331.      print "Setgid\n" if -g _;
  1332.      print "Sticky\n" if -k _;
  1333.      print "Text\n" if -T _;
  1334.      print "Binary\n" if -B _;
  1335.  
  1336.  
  1337. Here is what C has that perl doesn't:
  1338.  
  1339. unary &     Address-of operator.
  1340.  
  1341. unary *     Dereference-address operator.
  1342.  
  1343. (TYPE)      Type casting operator.
  1344.  
  1345. Like C, perl does a certain amount of expression evaluation at
  1346. compile time, whenever it determines that all of the arguments to
  1347. an operator are static and have no side effects.  In particular,
  1348. string concatenation happens at compile time between literals
  1349. that don't do variable substitution.  Backslash interpretation
  1350. also happens at compile time.  You can say
  1351.  
  1352.      'Now is the time for all' . "\n" .
  1353.      'good men to come to.'
  1354.  
  1355. and this all reduces to one string internally.
  1356.  
  1357. The autoincrement operator has a little extra built-in magic to
  1358. it.  If you increment a variable that is numeric, or that has
  1359. ever been used in a numeric context, you get a normal increment.
  1360. If, however, the variable has only been used in string contexts
  1361. since it was set, and has a value that is not null and matches
  1362. the pattern /^[a-zA-Z]*[0-9]*$/, the increment is done as a
  1363. string, preserving each character within its range, with carry:
  1364.  
  1365.      print ++($foo = '99');   # prints '100'
  1366.      print ++($foo = 'a0');   # prints 'a1'
  1367.      print ++($foo = 'Az');   # prints 'Ba'
  1368.      print ++($foo = 'zz');   # prints 'aaa'
  1369.  
  1370. The autodecrement is not magical.
  1371.  
  1372. The range operator (in an array context) makes use of the magical
  1373. autoincrement algorithm if the minimum and maximum are strings.
  1374. You can say
  1375.  
  1376.      @alphabet = ('A' .. 'Z');
  1377.  
  1378. to get all the letters of the alphabet, or
  1379.  
  1380.      $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
  1381.  
  1382. to get a hexadecimal digit, or
  1383.  
  1384.      @z2 = ('01' .. '31');  print @z2[$mday];
  1385.  
  1386. to get dates with leading zeros.  (If the final value specified
  1387. is not in the sequence that the magical increment would produce,
  1388. the sequence goes until the next value would be longer than the
  1389. final value specified.)
  1390.  
  1391. The || and && operators differ from C's in that, rather than
  1392. returning 0 or 1, they return the last value evaluated. Thus, a
  1393. portable way to find out the home directory might be:
  1394.  
  1395.      $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  1396.                (getpwuid($<))[7] || die "You're homeless!\n";
  1397.  
  1398. ╛KY Perl╔Operators
  1399. ╛C Along with the literals and variables mentioned earlier, the
  1400. operations in the following section can serve as terms in an
  1401. expression.  Some of these operations take a LIST as an argument.
  1402.  
  1403. Such a list can consist of any combination of scalar arguments or
  1404. array values; the array values will be included in the list as if
  1405. each individual element were interpolated at that point in the
  1406. list, forming a longer single-dimensional array value.  Elements
  1407. of the LIST should be separated by commas.  If an operation is
  1408. listed both with and without parentheses around its arguments, it
  1409. means you can either use it as a unary operator or as a function
  1410. call.  To use it as a function call, the next token on the same
  1411. line must be a left parenthesis.  (There may be intervening white
  1412. space.) Such a function then has highest precedence, as you would
  1413. expect from a function.  If any token other than a left
  1414. parenthesis follows, then it is a unary operator, with a pre-
  1415. cedence depending only on whether it is a LIST operator or not.
  1416. LIST operators have lowest precedence.  All other unary operators
  1417. have a precedence greater than relational operators but less than
  1418. arithmetic operators.  See the section on Precedence.
  1419.  
  1420. ╛KL accept
  1421. alarm
  1422. atan2
  1423. bind
  1424. binmode
  1425. caller
  1426. chdir
  1427. chmod
  1428. chop
  1429. chown
  1430. chroot
  1431. close
  1432. closedir
  1433. connect
  1434. cos
  1435. crypt
  1436. dbmclose
  1437. dbmopen
  1438. defined
  1439. delete
  1440. die
  1441. do
  1442. do
  1443. do
  1444. dump
  1445. each
  1446. eof
  1447. eval
  1448. exec
  1449. exit
  1450. exp
  1451. fcntl
  1452. fileno
  1453. flock
  1454. fork
  1455. getc
  1456. getlogin
  1457. getpeername
  1458. getpgrp
  1459. getppid
  1460. getpwnam
  1461. getsockname
  1462. getsockopt
  1463. gmtime
  1464. goto
  1465. grep
  1466. hex
  1467. index
  1468. int
  1469. ioctl
  1470. join
  1471. keys
  1472. kill
  1473. last
  1474. length
  1475. link
  1476. listen
  1477. local
  1478. localtime
  1479. log
  1480. lstat
  1481. m
  1482. mkdir
  1483. msgctl
  1484. msgget
  1485. msgsnd
  1486. msgrcv
  1487. next
  1488. oct
  1489. open
  1490. opendir
  1491. ord
  1492. pack
  1493. pipe
  1494. pop
  1495. print
  1496. printf
  1497. push
  1498. q
  1499. rand
  1500. read
  1501. readdir
  1502. readlink
  1503. recv
  1504. redo
  1505. rename
  1506. require
  1507. reset
  1508. return
  1509. reverse
  1510. rewinddir
  1511. rindex
  1512. rmdir
  1513. s
  1514. scalar
  1515. seek
  1516. seekdir
  1517. select
  1518. select
  1519. semctl
  1520. semget
  1521. semop
  1522. send
  1523. setpgrp
  1524. setpriority
  1525. setsockopt
  1526. shift
  1527. shmctl
  1528. shmget
  1529. shmread
  1530. shutdown
  1531. sin
  1532. sleep
  1533. socket
  1534. socketpair
  1535. sort
  1536. splice
  1537. split
  1538. sprintf
  1539. sqrt
  1540. srand
  1541. stat
  1542. study
  1543. substr
  1544. symlink
  1545. syscall
  1546. sysread
  1547. system
  1548. syswrite
  1549. tell
  1550. telldir
  1551. time
  1552. times
  1553. tr
  1554. truncate
  1555. umask
  1556. undef
  1557. unlink
  1558. unpack
  1559. unshift
  1560. utime
  1561. values
  1562. vec
  1563. wait
  1564. waitpid
  1565. wantarray
  1566. warn
  1567. write
  1568. ╛KY accept
  1569. ╛DT accept(NEWSOCKET,GENERICSOCKET)
  1570. ╛C accept(NEWSOCKET,GENERICSOCKET)
  1571.  
  1572.           Does the same thing that the accept system call does.
  1573.           Returns true if it succeeded, false otherwise.  See exam-
  1574.           ple in section on Interprocess Communication.
  1575. ╛KY alarm
  1576. ╛DT alarm(SECONDS)
  1577. ╛C alarm(SECONDS)
  1578. alarm SECONDS
  1579.  
  1580.           Arranges to have a SIGALRM delivered to this process
  1581.           after the specified number of seconds (minus 1, actually)
  1582.           have elapsed.  Thus, alarm(15) will cause a SIGALRM at
  1583.           some point more than 14 seconds in the future.  Only one
  1584.           timer may be counting at once.  Each call disables the
  1585.           previous timer, and an argument of 0 may be supplied to
  1586.           cancel the previous timer without starting a new one.
  1587.           The returned value is the amount of time remaining on the
  1588.           previous timer.
  1589. ╛KY atan2
  1590. ╛DT atan2(Y,X)
  1591. ╛C atan2(Y,X)
  1592.  
  1593.           Returns the arctangent of Y/X in the range -PI to PI.
  1594. ╛KY bind
  1595. ╛DT bind(SOCKET,NAME)
  1596. ╛C bind(SOCKET,NAME)
  1597.  
  1598.           Does the same thing that the bind system call does.
  1599.           Returns true if it succeeded, false otherwise.  NAME
  1600.           should be a packed address of the proper type for the
  1601.           socket.  See example in section on Interprocess
  1602.           Communication.
  1603. ╛KY binmode
  1604. ╛DT binmode(FILEHANDLE)
  1605. ╛C binmode(FILEHANDLE)
  1606. binmode FILEHANDLE
  1607.  
  1608.           Arranges for the file to be read in "binary" mode in
  1609.           operating systems that distinguish between binary and
  1610.           text files.  Files that are not read in binary mode have
  1611.           CR LF sequences translated to LF on input and LF
  1612.           translated to CR LF on output.  Binmode has no effect
  1613.           under Unix.  If FILEHANDLE is an expression, the value is
  1614.           taken as the name of the filehandle.
  1615. ╛KY caller
  1616. ╛DT caller(EXPR)
  1617. ╛C caller(EXPR)
  1618. caller  Returns the context of the current subroutine call:
  1619.  
  1620.                          ($package,$filename,$line) = caller;
  1621.  
  1622.           With EXPR, returns some extra information that the
  1623.           debugger uses to print a stack trace.  The value of EXPR
  1624.           indicates how many call frames to go back before the
  1625.           current one.
  1626. ╛KY chdir
  1627. ╛DT chdir(EXPR)
  1628. ╛C chdir(EXPR)
  1629. chdir EXPR
  1630.  
  1631.           Changes the working directory to EXPR, if possible.  If
  1632.           EXPR is omitted, changes to home directory.  Returns 1
  1633.           upon success, 0 otherwise.  See example under die.
  1634. ╛KY chmod
  1635. ╛DT chmod(LIST)
  1636. ╛C chmod(LIST)
  1637. chmod LIST
  1638.  
  1639.           Changes the permissions of a list of files.  The first
  1640.           element of the list must be the numerical mode.  Returns
  1641.           the number of files successfully changed.
  1642.  
  1643.                          $cnt = chmod 0755, 'foo', 'bar';
  1644.                          chmod 0755, @executables;
  1645. ╛KY chop
  1646. ╛DT chop(LIST)
  1647. ╛C chop(LIST)
  1648. chop(VARIABLE)
  1649. chop VARIABLE
  1650. chop    Chops off the last character of a string and returns the
  1651.  
  1652.           character chopped.  It's used primarily to remove the
  1653.           newline from the end of an input record, but is much more
  1654.           efficient than s/\n// because it neither scans nor copies
  1655.           the string.  If VARIABLE is omitted, chops $_.  Example:
  1656.  
  1657.                          while (<>) {
  1658.                               chop;     # avoid \n on last field
  1659.                               @array = split(/:/);
  1660.                               ...
  1661.                          }
  1662.  
  1663.           You can actually chop anything that's an lvalue, includ-
  1664.           ing an assignment:
  1665.  
  1666.                          chop($cwd = `pwd`);
  1667.                          chop($answer = <STDIN>);
  1668.  
  1669.           If you chop a list, each element is chopped.  Only the
  1670.           value of the last chop is returned.
  1671. ╛KY chown
  1672. ╛DT chown(LIST)
  1673. ╛C chown(LIST)
  1674. chown LIST
  1675.  
  1676.           Changes the owner (and group) of a list of files.  The
  1677.           first two elements of the list must be the NUMERICAL uid
  1678.           and gid, in that order.  Returns the number of files suc-
  1679.           cessfully changed.
  1680.  
  1681.                          $cnt = chown $uid, $gid, 'foo', 'bar';
  1682.                          chown $uid, $gid, @filenames;
  1683.  
  1684.           Here's an example of looking up non-numeric uids in the passwd file:
  1685.  
  1686.                          print "User: ";
  1687.                          $user = <STDIN>;
  1688.                          chop($user);
  1689.                          print "Files: "
  1690.                          $pattern = <STDIN>;
  1691.                          chop($pattern);
  1692.                          open(pass, '/etc/passwd')
  1693.                               || die "Can't open passwd: $!\n";
  1694.                          while (<pass>) {
  1695.                               ($login,$pass,$uid,$gid) = split(/:/);
  1696.                               $uid{$login} = $uid;
  1697.                               $gid{$login} = $gid;
  1698.                          }
  1699.                          @ary = <${pattern}>;     # get filenames
  1700.                          if ($uid{$user} eq '') {
  1701.                               die "$user not in passwd file";
  1702.                          }
  1703.                          else {
  1704.                               chown $uid{$user}, $gid{$user}, @ary;
  1705.                          }
  1706. ╛KY chroot
  1707. ╛DT chroot(FILENAME)
  1708. ╛C chroot(FILENAME)
  1709. chroot FILENAME
  1710.  
  1711.           Does the same as the system call of that name.  If you
  1712.           don't know what it does, don't worry about it.  If
  1713.           FILENAME is omitted, does chroot to $_.
  1714. ╛KY close
  1715. ╛DT close(FILEHANDLE)
  1716. ╛C close(FILEHANDLE)
  1717. close FILEHANDLE
  1718.  
  1719.           Closes the file or pipe associated with the file handle.
  1720.           You don't have to close FILEHANDLE if you are immediately
  1721.           going to do another open on it, since open will close it
  1722.           for you.  (See open.) However, an explicit close on an
  1723.           input file resets the line counter ($.), while the impli-
  1724.           cit close done by open does not.  Also, closing a pipe
  1725.           will wait for the process executing on the pipe to com-
  1726.           plete, in case you want to look at the output of the pipe
  1727.           afterwards.  Closing a pipe explicitly also puts the
  1728.           status value of the command into $?.  Example:
  1729.  
  1730.                          open(OUTPUT, '|sort >foo');   # pipe to sort
  1731.                          ...  # print stuff to output
  1732.                          close OUTPUT;       # wait for sort to finish
  1733.                          open(INPUT, 'foo'); # get sort's results
  1734.  
  1735.           FILEHANDLE may be an expression whose value gives the
  1736.           real filehandle name.
  1737. ╛KY closedir
  1738. ╛DT closedir(DIRHANDLE)
  1739. ╛C closedir(DIRHANDLE)
  1740. closedir DIRHANDLE
  1741.  
  1742.           Closes a directory opened by opendir().
  1743. ╛KY connect
  1744. ╛DT connect(SOCKET,NAME)
  1745. ╛C connect(SOCKET,NAME)
  1746.  
  1747.           Does the same thing that the connect system call does.
  1748.           Returns true if it succeeded, false otherwise.  NAME
  1749.           should be a package address of the proper type for the
  1750.           socket.  See example in section on Interprocess Communi-
  1751.           cation.
  1752. ╛KY cos
  1753. ╛DT cos(EXPR)
  1754. ╛C cos(EXPR)
  1755. cos EXPR
  1756.  
  1757.           Returns the cosine of EXPR (expressed in radians).  If
  1758.           EXPR is omitted takes cosine of $_.
  1759. ╛KY crypt
  1760. ╛DT crypt(PLAINTEXT,SALT)
  1761. ╛C crypt(PLAINTEXT,SALT)
  1762.  
  1763.           Encrypts a string exactly like the crypt() function in
  1764.           the C library.  Useful for checking the password file for
  1765.           lousy passwords.  Only the guys wearing white hats should
  1766.           do this.
  1767. ╛KY dbmclose
  1768. ╛DT dbmclose(ASSOC_ARRAY)
  1769. ╛C dbmclose(ASSOC_ARRAY)
  1770. dbmclose ASSOC_ARRAY
  1771.  
  1772.           Breaks the binding between a dbm file and an associative
  1773.           array.  The values remaining in the associative array are
  1774.           meaningless unless you happen to want to know what was in
  1775.           the cache for the dbm file.  This function is only useful
  1776.           if you have ndbm.
  1777. ╛KY dbmopen
  1778. ╛DT dbmopen(ASSOC,DBNAME,MODE)
  1779. ╛C dbmopen(ASSOC,DBNAME,MODE)
  1780.  
  1781.           This binds a dbm or ndbm file to an associative array.
  1782.           ASSOC is the name of the associative array.  (Unlike nor-
  1783.           mal open, the first argument is NOT a filehandle, even
  1784.           though it looks like one).  DBNAME is the name of the
  1785.           database (without the .dir or .pag extension).  If the
  1786.           database does not exist, it is created with protection
  1787.           specified by MODE (as modified by the umask).  If your
  1788.           system only supports the older dbm functions, you may
  1789.           perform only one dbmopen in your program.  If your system
  1790.           has neither dbm nor ndbm, calling dbmopen produces a
  1791.           fatal error.
  1792.  
  1793.           Values assigned to the associative array prior to the
  1794.           dbmopen are lost.  A certain number of values from the
  1795.           dbm file are cached in memory.  By default this number is
  1796.           64, but you can increase it by preallocating that number
  1797.           of garbage entries in the associative array before the
  1798.           dbmopen.  You can flush the cache if necessary with the
  1799.           reset command.
  1800.  
  1801.           If you don't have write access to the dbm file, you can
  1802.           only read associative array variables, not set them.  If
  1803.           you want to test whether you can write, either use file
  1804.           tests or try setting a dummy array entry inside an eval,
  1805.           which will trap the error.
  1806.  
  1807.           Note that functions such as keys() and values() may
  1808.           return huge array values when used on large dbm files.
  1809.           You may prefer to use the each() function to iterate over
  1810.           large dbm files.  Example:
  1811.  
  1812.                          # print out history file offsets
  1813.                          dbmopen(HIST,'/usr/lib/news/history',0666);
  1814.                          while (($key,$val) = each %HIST) {
  1815.                               print $key, ' = ', unpack('L',$val), "\n";
  1816.                          }
  1817.                          dbmclose(HIST);
  1818. ╛KY defined
  1819. ╛DT defined(EXPR)
  1820. ╛C defined(EXPR)
  1821. defined EXPR
  1822.  
  1823.           Returns a boolean value saying whether the lvalue EXPR
  1824.           has a real value or not.  Many operations return the
  1825.           undefined value under exceptional conditions, such as end
  1826.           of file, uninitialized variable, system error and such.
  1827.           This function allows you to distinguish between an unde-
  1828.           fined null string and a defined null string with opera-
  1829.           tions that might return a real null string, in particular
  1830.           referencing elements of an array.  You may also check to
  1831.           see if arrays or subroutines exist.  Use on predefined
  1832.           variables is not guaranteed to produce intuitive results.
  1833.           Examples:
  1834.  
  1835.                          print if defined $switch{'D'};
  1836.                          print "$val\n" while defined($val = pop(@ary));
  1837.                          die "Can't readlink $sym: $!"
  1838.                               unless defined($value = readlink $sym);
  1839.                          eval '@foo = ()' if defined(@foo);
  1840.                          die "No XYZ package defined" unless defined %_XYZ;
  1841.                          sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
  1842.  
  1843.           See also undef.
  1844. ╛KY delete
  1845. ╛DT delete $ASSOC{KEY}
  1846. ╛C delete $ASSOC{KEY}
  1847.  
  1848.           Deletes the specified value from the specified associa-
  1849.           tive array.  Returns the deleted value, or the undefined
  1850.           value if nothing was deleted.  Deleting from $ENV{} modi-
  1851.           fies the environment.  Deleting from an array bound to a
  1852.           dbm file deletes the entry from the dbm file.
  1853.  
  1854.           The following deletes all the values of an associative
  1855.           array:
  1856.  
  1857.                          foreach $key (keys %ARRAY) {
  1858.                               delete $ARRAY{$key};
  1859.                          }
  1860.  
  1861.           (But it would be faster to use the reset command.  Saying
  1862.           undef %ARRAY is faster yet.)
  1863. ╛KY die
  1864. ╛DT die(LIST)
  1865. ╛C die(LIST)
  1866. die LIST
  1867.  
  1868.           Outside of an eval, prints the value of LIST to STDERR
  1869.           and exits with the current value of $!  (errno).  If $!
  1870.           is 0, exits with the value of ($? >> 8) (`command`
  1871.           status).  If ($? >> 8) is 0, exits with 255.  Inside an
  1872.           eval, the error message is stuffed into $@ and the eval
  1873.           is terminated with the undefined value.
  1874.  
  1875.           Equivalent examples:
  1876.  
  1877.                          die "Can't cd to spool: $!\n"
  1878.                               unless chdir '/usr/spool/news';
  1879.  
  1880.                          chdir '/usr/spool/news' || die "Can't cd to spool: $!\n"
  1881.  
  1882.  
  1883.           If the value of EXPR does not end in a newline, the
  1884.           current script line number and input line number (if any)
  1885.           are also printed, and a newline is supplied.  Hint: some-
  1886.           times appending ", stopped" to your message will cause it
  1887.           to make better sense when the string "at foo line 123" is
  1888.           appended.  Suppose you are running script "canasta".
  1889.  
  1890.                          die "/etc/games is no good";
  1891.                          die "/etc/games is no good, stopped";
  1892.  
  1893.           produce, respectively
  1894.  
  1895.                          /etc/games is no good at canasta line 123.
  1896.                          /etc/games is no good, stopped at canasta line 123.
  1897.  
  1898.           See also exit.
  1899. ╛KY do
  1900. ╛DT do BLOCK
  1901. ╛C do BLOCK
  1902.  
  1903.           Returns the value of the last command in the sequence of
  1904.           commands indicated by BLOCK.  When modified by a loop
  1905.           modifier, executes the BLOCK once before testing the loop
  1906.           condition.  (On other statements the loop modifiers test
  1907.           the conditional first.)
  1908.  
  1909. do SUBROUTINE (LIST)
  1910.  
  1911.           Executes a SUBROUTINE declared by a sub declaration, and
  1912.           returns the value of the last expression evaluated in
  1913.           SUBROUTINE.  If there is no subroutine by that name, pro-
  1914.           duces a fatal error.  (You may use the "defined" operator
  1915.           to determine if a subroutine exists.) If you pass arrays
  1916.           as part of LIST you may wish to pass the length of the
  1917.           array in front of each array.  (See the section on sub-
  1918.           routines later on.) SUBROUTINE may be a scalar variable,
  1919.           in which case the name of the sub routine to execute is
  1920.           taken from the variable.  The parentheses are required to
  1921.           avoid confusion with the "do EXPR" form.
  1922.  
  1923.           As an alternate form, you may call a subroutine by pre-
  1924.           fixing the name with an ampersand: &foo(@args).  If you
  1925.           aren't passing any arguments, you don't have to use
  1926.           parentheses.  If you omit the parentheses, no @_ array is
  1927.           passed to the subroutine.  The & form is also used to
  1928.           specify subroutines to the defined and undef operators:
  1929.           
  1930.                          if (defined &$var) { &$var($parm); undef &$var; }
  1931.  
  1932. do EXPR
  1933.  
  1934.           Uses the value of EXPR as a filename and executes the
  1935.           contents of the file as a perl script.  Its primary use
  1936.           is to include subroutines from a perl subroutine library.
  1937.  
  1938.                          do 'stat.pl';
  1939.  
  1940.           is just like
  1941.  
  1942.                          eval `cat stat.pl`;
  1943.  
  1944.           except that it's more efficient, more concise, keeps
  1945.           track of the current filename for error messages, and
  1946.           searches all the -I libraries if the file isn't in the
  1947.           current directory (see also the @INC array in Predefined
  1948.           Names).  It's the same, however, in that it does reparse
  1949.           the file every time you call it, so if you are going to
  1950.           use the file inside a loop you might prefer to use -P and
  1951.           #include, at the expense of a little more startup time.
  1952.           (The main problem with #include is that cpp doesn't grok
  1953.           # comments--a workaround is to use ";#" for standalone
  1954.           comments.) Note that the following are NOT equivalent:
  1955.  
  1956.                          do $foo;  # eval a file
  1957.                          do $foo();     # call a subroutine
  1958.  
  1959.           Note that inclusion of library routines is better done
  1960.           with the "require" operator.
  1961. ╛KY dump
  1962. ╛DT dump LABEL
  1963. ╛C dump LABEL
  1964.  
  1965.           This causes an immediate core dump.  Primarily this is so
  1966.           that you can use the undump program to turn your core
  1967.           dump into an executable binary after having initialized
  1968.           all your variables at the beginning of the program.  When
  1969.           the new binary is executed it will begin by executing a
  1970.           "goto LABEL" (with all the restrictions that goto
  1971.           suffers).  Think of it as a goto with an intervening core
  1972.           dump and reincarnation.  If LABEL is omitted, restarts
  1973.           the program from the top.  WARNING: any files opened at
  1974.           the time of the dump will NOT be open any more when the
  1975.           program is reincarnated, with possible resulting confu-
  1976.           sion on the part of perl.  See also -u.
  1977.  
  1978.           Example:
  1979.  
  1980.                          #!/usr/bin/perl
  1981.                          require 'getopt.pl';
  1982.                          require 'stat.pl';
  1983.                          %days = (
  1984.                          'Sun',1,
  1985.                          'Mon',2,
  1986.                          'Tue',3,
  1987.                          'Wed',4,
  1988.                          'Thu',5,
  1989.                          'Fri',6,
  1990.                          'Sat',7);
  1991.  
  1992.                          dump QUICKSTART if $ARGV[0] eq '-d';
  1993.  
  1994.                     QUICKSTART:
  1995.                          do Getopt('f');
  1996. ╛KY each
  1997. ╛DT each(ASSOC_ARRAY)
  1998. ╛C each(ASSOC_ARRAY)
  1999. each ASSOC_ARRAY
  2000.  
  2001.           Returns a 2 element array consisting of the key and value
  2002.           for the next value of an associative array, so that you
  2003.           can iterate over it.  Entries are returned in an
  2004.           apparently random order.  When the array is entirely
  2005.           read, a null array is returned (which when assigned pro-
  2006.           duces a FALSE (0) value).  The next call to each() after
  2007.           that will start iterating again.  The iterator can be
  2008.           reset only by reading all the elements from the array.
  2009.           You must not modify the array while iterating over it.
  2010.           There is a single iterator for each associative array,
  2011.           shared by all each(), keys() and values() function calls
  2012.           in the program.  The following prints out your environ-
  2013.           ment like the printenv program, only in a different
  2014.           order:
  2015.  
  2016.                          while (($key,$value) = each %ENV) {
  2017.                               print "$key=$value\n";
  2018.                          }
  2019.  
  2020.           See also keys() and values().
  2021. ╛KY eof
  2022. ╛DT eof(FILEHANDLE)
  2023. ╛C eof(FILEHANDLE)
  2024. eof()
  2025. eof
  2026.           Returns 1 if the next read on FILEHANDLE will return end
  2027.           of file, or if FILEHANDLE is not open.  FILEHANDLE may be
  2028.           an expression whose value gives the real filehandle name.
  2029.           (Note that this function actually reads a character and
  2030.           then ungetc's it, so it is not very useful in an interac-
  2031.           tive context.) An eof without an argument returns the eof
  2032.           status for the last file read.  Empty parentheses () may
  2033.           be used to indicate the pseudo file formed of the files
  2034.           listed on the command line, i.e. eof() is reasonable to
  2035.           use inside a while (<>) loop to detect the end of only
  2036.           the last file.  Use eof(ARGV) or eof without the
  2037.           parentheses to test EACH file in a while (<>) loop.
  2038.           Examples:
  2039.  
  2040.                          # insert dashes just before last line of last file
  2041.                          while (<>) {
  2042.                               if (eof()) {
  2043.                                    print "--------------\n";
  2044.                               }
  2045.                               print;
  2046.                          }
  2047.  
  2048.                          # reset line numbering on each input file
  2049.                          while (<>) {
  2050.                               print "$.\t$_";
  2051.                               if (eof) {     # Not eof().
  2052.                                    close(ARGV);
  2053.                               }
  2054.                          }
  2055. ╛KY eval
  2056. ╛DT eval(EXPR)
  2057. ╛C eval(EXPR)
  2058. eval EXPR
  2059. eval BLOCK
  2060.  
  2061.           EXPR is parsed and executed as if it were a little perl
  2062.           program.  It is executed in the context of the current
  2063.           perl program, so that any variable settings, subroutine
  2064.           or format definitions remain afterwards.  The value
  2065.           returned is the value of the last expression evaluated,
  2066.           just as with subroutines.  If there is a syntax error or
  2067.           runtime error, or a die statement is executed, an unde-
  2068.           fined value is returned by eval, and $@ is set to the
  2069.           error message.  If there was no error, $@ is guaranteed
  2070.           to be a null string.  If EXPR is omitted, evaluates $_.
  2071.           The final semicolon, if any, may be omitted from the
  2072.           expression.
  2073.  
  2074.           Note that, since eval traps otherwise-fatal errors, it is
  2075.           useful for determining whether a particular feature (such
  2076.           as dbmopen or symlink) is implemented.  It is also Perl's
  2077.           exception trapping mechanism, where the die operator is
  2078.           used to raise exceptions.
  2079.  
  2080.           If the code to be executed doesn't vary, you may use the 
  2081.           eval-BLOCK form to trap run-time errors without incurring
  2082.           the penalty of recompiling each time. The error, if any, 
  2083.           is still returned in $@.
  2084.           Evaluating a single-quoted string (as EXPR) has the same 
  2085.           effect, except that the eval-EXPR form reports syntax errors 
  2086.           at run time via $@, whereas the eval-BLOCK form reports syntax 
  2087.           errors at compile time.  The eval-EXPR form is optimized to 
  2088.           eval-BLOCK the first time it succeeds.  (Since the replacement
  2089.           side of a substitution is considered a single-quoted string 
  2090.           when you use the e modifier, the same optimization occurs there.) 
  2091.           Examples:
  2092.  
  2093.                         # make divide-by-zero non-fatal
  2094.                         eval { $answer = $a / $b; }; warn $@ if $@;
  2095.  
  2096.                         # optimized to same thing after first use
  2097.                         eval '$answer = $a / $b'; warn $@ if $@;
  2098.  
  2099.                         # a compile-time error
  2100.                         eval { $answer = };
  2101.  
  2102.                         # a run-time error
  2103.                         eval '$answer =';    # sets $@
  2104.                         
  2105. ╛KY exec
  2106. ╛DT exec(LIST)
  2107. ╛C exec(LIST)
  2108. exec LIST
  2109.  
  2110.           If there is more than one argument in LIST, or if LIST is
  2111.           an array with more than one value, calls execvp() with
  2112.           the arguments in LIST.  If there is only one scalar argu-
  2113.           ment, the argument is checked for shell metacharacters.
  2114.           If there are any, the entire argument is passed to
  2115.           "/bin/sh -c" for parsing.  If there are none, the argu-
  2116.           ment is split into words and passed directly to execvp(),
  2117.           which is more efficient.  Note: exec (and system) do not
  2118.           flush your output buffer, so you may need to set $| to
  2119.           avoid lost output.  Examples:
  2120.  
  2121.                          exec '/bin/echo', 'Your arguments are: ', @ARGV;
  2122.                          exec "sort $outfile | uniq";
  2123.  
  2124.  
  2125.           If you don't really want to execute the first argument,
  2126.           but want to lie to the program you are executing about
  2127.           its own name, you can specify the program you actually
  2128.           want to run by assigning that to a variable and putting
  2129.           the name of the variable in front of the LIST without a
  2130.           comma.  (This always forces interpretation of the LIST as
  2131.           a multi-valued list, even if there is only a single
  2132.           scalar in the list.) Example:
  2133.  
  2134.                          $shell = '/bin/csh';
  2135.                          exec $shell '-sh';       # pretend it's a login shell
  2136. ╛KY exit
  2137. ╛DT exit(EXPR)
  2138. ╛C exit(EXPR)
  2139. exit EXPR
  2140.  
  2141.           Evaluates EXPR and exits immediately with that value.
  2142.           Example:
  2143.  
  2144.                          $ans = <STDIN>;
  2145.                          exit 0 if $ans =~ /^[Xx]/;
  2146.  
  2147.           See also die.  If EXPR is omitted, exits with 0 status.
  2148. ╛KY exp
  2149. ╛DT exp(EXPR)
  2150. ╛C exp(EXPR)
  2151. exp EXPR
  2152.  
  2153.           Returns e to the power of EXPR.  If EXPR is omitted,
  2154.           gives exp($_).
  2155. ╛KY fcntl
  2156. ╛DT fcntl(FILEHANDLE,FUNCTION,SCALAR)
  2157. ╛C fcntl(FILEHANDLE,FUNCTION,SCALAR)
  2158.  
  2159.           Implements the fcntl(2) function.  You'll probably have
  2160.           to say
  2161.  
  2162.                          require "fcntl.ph"; # probably /usr/local/lib/perl/fcntl.ph
  2163.  
  2164.           first to get the correct function definitions.  If
  2165.           fcntl.ph doesn't exist or doesn't have the correct defin-
  2166.           itions you'll have to roll your own, based on your C
  2167.           header files such as <sys/fcntl.h>.  (There is a perl
  2168.           script called h2ph that comes with the perl kit which may
  2169.           help you in this.) Argument processing and value return
  2170.           works just like ioctl below.  Note that fcntl will pro-
  2171.           duce a fatal error if used on a machine that doesn't
  2172.           implement fcntl(2).
  2173. ╛KY fileno
  2174. ╛DT fileno(FILEHANDLE)
  2175. ╛C fileno(FILEHANDLE)
  2176. fileno FILEHANDLE
  2177.  
  2178.           Returns the file descriptor for a filehandle.  Useful for
  2179.           constructing bitmaps for select().  If FILEHANDLE is an
  2180.           expression, the value is taken as the name of the
  2181.           filehandle.
  2182. ╛KY flock
  2183. ╛DT flock(FILEHANDLE,OPERATION)
  2184. ╛C flock(FILEHANDLE,OPERATION)
  2185.  
  2186.           Calls flock(2) on FILEHANDLE.  See manual page for
  2187.           flock(2) for definition of OPERATION.  Returns true for
  2188.           success, false on failure.  Will produce a fatal error if
  2189.           used on a machine that doesn't implement flock(2).
  2190.           Here's a mailbox appender for BSD systems.
  2191.  
  2192.                          $LOCK_SH = 1;
  2193.                          $LOCK_EX = 2;
  2194.                          $LOCK_NB = 4;
  2195.                          $LOCK_UN = 8;
  2196.  
  2197.                          sub lock {
  2198.                          flock(MBOX,$LOCK_EX);
  2199.                          # and, in case someone appended
  2200.                          # while we were waiting...
  2201.                          seek(MBOX, 0, 2);
  2202.                          }
  2203.  
  2204.                          sub unlock {
  2205.                          flock(MBOX,$LOCK_UN);
  2206.                          }
  2207.  
  2208.                          open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
  2209.                               || die "Can't open mailbox: $!";
  2210.  
  2211.                          do lock();
  2212.                          print MBOX $msg,"\n\n";
  2213.                          do unlock();
  2214. ╛KY fork
  2215. ╛DT fork    Does a fork() call.  Returns the child pid to the parent
  2216. ╛C fork
  2217.           Does a fork() call.  Returns the child pid to the parent
  2218.           process and 0 to the child process.  Note: unflushed
  2219.           buffers remain unflushed in both processes, which means
  2220.           you may need to set $| to avoid duplicate output.
  2221. ╛KY getc
  2222. ╛DT getc(FILEHANDLE)
  2223. ╛C getc(FILEHANDLE)
  2224. getc FILEHANDLE
  2225. getc
  2226.           Returns the next character from the input file attached
  2227.           to FILEHANDLE, or a null string at EOF.  If FILEHANDLE is
  2228.           omitted, reads from STDIN.
  2229. ╛KY getlogin
  2230. ╛DT getlogin
  2231. ╛C getlogin
  2232.  
  2233.           Returns the current login from /etc/utmp, if any.  If
  2234.           null, use getpwuid.
  2235.  
  2236.                          $login = getlogin || (getpwuid($<))[0] || "Some-
  2237.           body";
  2238. ╛KY getpeername
  2239. ╛DT getpeername(SOCKET)
  2240. ╛C getpeername(SOCKET)
  2241.  
  2242.           Returns the packed sockaddr address of other end of the
  2243.           SOCKET connection.
  2244.  
  2245.                          # An internet sockaddr
  2246.                          $sockaddr = 'S n a4 x8';
  2247.                          $hersockaddr = getpeername(S);
  2248.                          ($family, $port, $heraddr) =
  2249.                                    unpack($sockaddr,$hersockaddr);
  2250. ╛KY getpgrp
  2251. ╛DT getpgrp(PID)
  2252. ╛C getpgrp(PID)
  2253. getpgrp PID
  2254.  
  2255.           Returns the current process group for the specified PID,
  2256.           0 for the current process.  Will produce a fatal error if
  2257.           used on a machine that doesn't implement getpgrp(2).  If
  2258.           EXPR is omitted, returns process group of current pro-
  2259.           cess.
  2260. ╛KY getppid
  2261. ╛DT getppid
  2262. ╛C getppid
  2263.           Returns the process id of the parent process.
  2264. ╛KY getpriority
  2265. ╛DT getpriority(WHICH,WHO)
  2266. ╛C getpriority(WHICH,WHO)
  2267.  
  2268.           Returns the current priority for a process, a process
  2269.           group, or a user.  (See getpriority(2).) Will produce a
  2270.           fatal error if used on a machine that doesn't implement
  2271.           getpriority(2).
  2272. ╛KY getpwnam
  2273. ╛DT getpwnam(NAME)
  2274. ╛C getpwnam(NAME)
  2275. getgrnam(NAME)
  2276. gethostbyname(NAME)
  2277. getnetbyname(NAME)
  2278. getprotobyname(NAME)
  2279. getpwuid(UID)
  2280. getgrgid(GID)
  2281. getservbyname(NAME,PROTO)
  2282. gethostbyaddr(ADDR,ADDRTYPE)
  2283. getnetbyaddr(ADDR,ADDRTYPE)
  2284. getprotobynumber(NUMBER)
  2285. getservbyport(PORT,PROTO)
  2286. getpwent
  2287. getgrent
  2288. gethostent
  2289. getnetent
  2290. getprotoent
  2291. getservent
  2292. setpwent
  2293. setgrent
  2294. sethostent(STAYOPEN)
  2295. setnetent(STAYOPEN)
  2296. setprotoent(STAYOPEN)
  2297. setservent(STAYOPEN)
  2298. endpwent
  2299. endgrent
  2300. endhostent
  2301. endnetent
  2302. endprotoent
  2303. endservent
  2304.  
  2305.           These routines perform the same functions as their coun-
  2306.           terparts in the system library.  The return values from
  2307.           the various get routines are as follows:
  2308.  
  2309.                          ($name,$passwd,$uid,$gid,
  2310.                               $quota,$comment,$gcos,$dir,$shell) = getpw...
  2311.                          ($name,$passwd,$gid,$members) = getgr...
  2312.                          ($name,$aliases,$addrtype,$length,@addrs) = gethost...
  2313.                          ($name,$aliases,$addrtype,$net) = getnet...
  2314.                          ($name,$aliases,$proto) = getproto...
  2315.                          ($name,$aliases,$port,$proto) = getserv...
  2316.  
  2317.           The $members value returned by getgr... is a space
  2318.           separated list of the login names of the members of the
  2319.           group.
  2320.  
  2321.           The @addrs value returned by the gethost... functions is
  2322.           a list of the raw addresses returned by the corresponding
  2323.           system library call.  In the Internet domain, each
  2324.           address is four bytes long and you can unpack it by say-
  2325.           ing something like:
  2326.  
  2327.                          ($a,$b,$c,$d) = unpack('C4',$addr[0]);
  2328. ╛KY getsockname
  2329. ╛DT getsockname(SOCKET)
  2330. ╛C getsockname(SOCKET)
  2331.  
  2332.           Returns the packed sockaddr address of this end of the
  2333.           SOCKET connection.
  2334.  
  2335.                          # An internet sockaddr
  2336.                          $sockaddr = 'S n a4 x8';
  2337.                          $mysockaddr = getsockname(S);
  2338.                          ($family, $port, $myaddr) =
  2339.                                    unpack($sockaddr,$mysockaddr);
  2340. ╛KY getsockopt
  2341. ╛DT getsockopt(SOCKET,LEVEL,OPTNAME)
  2342. ╛C getsockopt(SOCKET,LEVEL,OPTNAME)
  2343.  
  2344.           Returns the socket option requested, or undefined if
  2345.           there is an error.
  2346. ╛KY gmtime
  2347. ╛DT gmtime(EXPR)
  2348. ╛C gmtime(EXPR)
  2349. gmtime EXPR
  2350.  
  2351.           Converts a time as returned by the time function to a 9-
  2352.           element array with the time analyzed for the Greenwich
  2353.           timezone.  Typically used as follows:
  2354.  
  2355.           ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  2356.                                                             gmtime(time);
  2357.  
  2358.           All array elements are numeric, and come straight out of
  2359.           a struct tm.  In particular this means that $mon has the
  2360.           range 0..11 and $wday has the range 0..6.  If EXPR is
  2361.           omitted, does gmtime(time).
  2362. ╛KY goto
  2363. ╛DT goto LABEL
  2364. ╛C goto LABEL
  2365.  
  2366.           Finds the statement labeled with LABEL and resumes execu-
  2367.           tion there.  Currently you may only go to statements in
  2368.           the main body of the program that are not nested inside a
  2369.           do {} construct.  This statement is not implemented very
  2370.           efficiently, and is here only to make the sed-to-perl
  2371.           translator easier.  I may change its semantics at any
  2372.           time, consistent with support for translated sed scripts.
  2373.           Use it at your own risk.  Better yet, don't use it at
  2374.           all.
  2375. ╛KY grep
  2376. ╛DT grep(EXPR,LIST)
  2377. ╛C grep(EXPR,LIST)
  2378.  
  2379.           Evaluates EXPR for each element of LIST (locally setting
  2380.           $_ to each element) and returns the array value consist-
  2381.           ing of those elements for which the expression evaluated
  2382.           to true.  In a scalar context, returns the number of
  2383.           times the expression was true.
  2384.  
  2385.                          @foo = grep(!/^#/, @bar);    # weed out comments
  2386.  
  2387.           Note that, since $_ is a reference into the array value,
  2388.           it can be used to modify the elements of the array.
  2389.           While this is useful and supported, it can cause bizarre
  2390.           results if the LIST is not a named array.
  2391. ╛KY hex
  2392. ╛DT hex(EXPR)
  2393. ╛C hex(EXPR)
  2394. hex EXPR
  2395.  
  2396.           Returns the decimal value of EXPR interpreted as an hex
  2397.           string.  (To interpret strings that might start with 0 or
  2398.           0x see oct().) If EXPR is omitted, uses $_.
  2399. ╛KY index
  2400. ╛DT index(STR,SUBSTR,POSITION)
  2401. ╛C index(STR,SUBSTR,POSITION)
  2402. index(STR,SUBSTR)
  2403.  
  2404.           Returns the position of the first occurrence of SUBSTR in
  2405.           STR at or after POSITION.  If POSITION is omitted, starts
  2406.           searching from the beginning of the string.  The return
  2407.           value is based at 0, or whatever you've set the $[ vari-
  2408.           able to.  If the substring is not found, returns one less
  2409.           than the base, ordinarily -1.
  2410. ╛KY int
  2411. ╛DT int(EXPR)
  2412. ╛C int(EXPR)
  2413. int EXPR
  2414.  
  2415.           Returns the integer portion of EXPR.  If EXPR is omitted,
  2416.           uses $_.
  2417. ╛KY ioctl
  2418. ╛DT ioctl(FILEHANDLE,FUNCTION,SCALAR)
  2419. ╛C ioctl(FILEHANDLE,FUNCTION,SCALAR)
  2420.  
  2421.           Implements the ioctl(2) function.  You'll probably have
  2422.           to say
  2423.  
  2424.                          require "ioctl.ph"; # probably /usr/local/lib/perl/ioctl.ph
  2425.  
  2426.           first to get the correct function definitions.  If
  2427.           ioctl.ph doesn't exist or doesn't have the correct defin-
  2428.           itions you'll have to roll your own, based on your C
  2429.           header files such as <sys/ioctl.h>.  (There is a perl
  2430.           script called h2ph that comes with the perl kit which may
  2431.           help you in this.) SCALAR will be read and/or written
  2432.           depending on the FUNCTION--a pointer to the string value
  2433.           of SCALAR will be passed as the third argument of the
  2434.           actual ioctl call.  (If SCALAR has no string value but
  2435.           does have a numeric value, that value will be passed
  2436.           rather than a pointer to the string value.  To guarantee
  2437.           this to be true, add a 0 to the scalar before using it.)
  2438.           The pack() and unpack() functions are useful for manipu-
  2439.           lating the values of structures used by ioctl().  The
  2440.           following example sets the erase character to DEL.
  2441.  
  2442.                          require 'ioctl.ph';
  2443.                          $sgttyb_t = "ccccs";          # 4 chars and a short
  2444.                          if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
  2445.                               @ary = unpack($sgttyb_t,$sgttyb);
  2446.                               $ary[2] = 127;
  2447.                               $sgttyb = pack($sgttyb_t,@ary);
  2448.                               ioctl(STDIN,$TIOCSETP,$sgttyb)
  2449.                                    || die "Can't ioctl: $!";
  2450.                          }
  2451.  
  2452.           The return value of ioctl (and fcntl) is as follows:
  2453.  
  2454.                          if OS returns:           perl returns:
  2455.                          -1                       undefined value
  2456.                          0                        string "0 but true"
  2457.                          anything else            that number
  2458.  
  2459.           Thus perl returns true on success and false on failure,
  2460.           yet you can still easily determine the actual value
  2461.           returned by the operating system:
  2462.  
  2463.                          ($retval = ioctl(...)) || ($retval = -1);
  2464.                          printf "System returned %d\n", $retval;
  2465. ╛KY join
  2466. ╛DT join(EXPR,LIST)
  2467. ╛C join(EXPR,LIST)
  2468. join(EXPR,ARRAY)
  2469.  
  2470.           Joins the separate strings of LIST or ARRAY into a single
  2471.           string with fields separated by the value of EXPR, and
  2472.           returns the string.  Example:
  2473.  
  2474.           $_ = join(':',
  2475.                               $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  2476.  
  2477.           See split.
  2478. ╛KY keys
  2479. ╛DT keys(ASSOC_ARRAY)
  2480. ╛C keys(ASSOC_ARRAY)
  2481. keys ASSOC_ARRAY
  2482.  
  2483.           Returns a normal array consisting of all the keys of the
  2484.           named associative array.  The keys are returned in an
  2485.           apparently random order, but it is the same order as
  2486.           either the values() or each() function produces (given
  2487.           that the associative array has not been modified).  Here
  2488.           is yet another way to print your environment:
  2489.  
  2490.                          @keys = keys %ENV;
  2491.                          @values = values %ENV;
  2492.                          while ($#keys >= 0) {
  2493.                               print pop(@keys), '=', pop(@values), "\n";
  2494.                          }
  2495.  
  2496.           or how about sorted by key:
  2497.  
  2498.                          foreach $key (sort(keys %ENV)) {
  2499.                               print $key, '=', $ENV{$key}, "\n";
  2500.                          }
  2501. ╛KY kill
  2502. ╛DT kill(LIST)
  2503. ╛C kill(LIST)
  2504. kill LIST
  2505.  
  2506.           Sends a signal to a list of processes.  The first element
  2507.           of the list must be the signal to send.  Returns the
  2508.           number of processes successfully signaled.
  2509.  
  2510.                          $cnt = kill 1, $child1, $child2;
  2511.                          kill 9, @goners;
  2512.  
  2513.           If the signal is negative, kills process groups instead
  2514.           of processes.  (On System V, a negative process number
  2515.           will also kill process groups, but that's not portable.)
  2516.           You may use a signal name in quotes.
  2517. ╛KY last
  2518. ╛DT last LABEL
  2519. ╛C last LABEL
  2520. last
  2521.           The last command is like the break statement in C (as
  2522.           used in loops); it immediately exits the loop in ques-
  2523.           tion.  If the LABEL is omitted, the command refers to the
  2524.           innermost enclosing loop.  The continue block, if any, is
  2525.           not executed:
  2526.  
  2527.                          line: while (<STDIN>) {
  2528.                               last line if /^$/;  # exit when done with header
  2529.                               ...
  2530.                          }
  2531. ╛KY length
  2532. ╛DT length(EXPR)
  2533. ╛C length(EXPR)
  2534. length EXPR
  2535.  
  2536.           Returns the length in characters of the value of EXPR.
  2537.           If EXPR is omitted, returns length of $_.
  2538. ╛KY link
  2539. ╛DT link(OLDFILE,NEWFILE)
  2540. ╛C link(OLDFILE,NEWFILE)
  2541.  
  2542.           Creates a new filename linked to the old filename.
  2543.           Returns 1 for success, 0 otherwise.
  2544. ╛KY listen
  2545. ╛DT listen(SOCKET,QUEUESIZE)
  2546. ╛C listen(SOCKET,QUEUESIZE)
  2547.  
  2548.           Does the same thing that the listen system call does.
  2549.           Returns true if it succeeded, false otherwise.  See exam-
  2550.           ple in section on Interprocess Communication.
  2551. ╛KY local
  2552. ╛DT local(LIST)
  2553. ╛C local(LIST)
  2554.  
  2555.           Declares the listed variables to be local to the enclos-
  2556.           ing block, subroutine, eval or "do".  All the listed ele-
  2557.           ments must be legal lvalues.  This operator works by sav-
  2558.           ing the current values of those variables in LIST on a
  2559.           hidden stack and restoring them upon exiting the block,
  2560.           subroutine or eval.  This means that called subroutines
  2561.           can also reference the local variable, but not the global
  2562.           one.  The LIST may be assigned to if desired, which
  2563.           allows you to initialize your local variables.  (If no
  2564.           initializer is given for a particular variable, it is
  2565.           created with an undefined value.) Commonly this is used
  2566.           to name the parameters to a subroutine.  Examples:
  2567.  
  2568.                          sub RANGEVAL {
  2569.                               local($min, $max, $thunk) = @_;
  2570.                               local($result) = '';
  2571.                               local($i);
  2572.  
  2573.                               # Presumably $thunk makes reference to $i
  2574.  
  2575.                               for ($i = $min; $i < $max; $i++) {
  2576.                                    $result .= eval $thunk;
  2577.                               }
  2578.  
  2579.                               $result;
  2580.                          }
  2581.  
  2582.                          if ($sw eq '-v') {
  2583.                          # init local array with global array
  2584.                          local(@ARGV) = @ARGV;
  2585.                          unshift(@ARGV,'echo');
  2586.                          system @ARGV;
  2587.                          }
  2588.                          # @ARGV restored
  2589.  
  2590.                          # temporarily add to digits associative array
  2591.                          if ($base12) {
  2592.                               # (NOTE: not claiming this is efficient!)
  2593.                               local(%digits) = (%digits,'t',10,'e',11);
  2594.                               do parse_num();
  2595.                          }
  2596.  
  2597.           Note that local() is a run-time command, and so gets exe-
  2598.           cuted every time through a loop, using up more stack
  2599.           storage each time until it's all released at once when
  2600.           the loop is exited.
  2601. ╛KY localtime
  2602. ╛DT localtime(EXPR)
  2603. ╛C localtime(EXPR)
  2604. localtime EXPR
  2605.  
  2606.           Converts a time as returned by the time function to a 9-
  2607.           element array with the time analyzed for the local
  2608.           timezone.  Typically used as follows:
  2609.  
  2610.           ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  2611.                                                             localtime(time);
  2612.  
  2613.           All array elements are numeric, and come straight out of
  2614.           a struct tm.  In particular this means that $mon has the
  2615.           range 0..11 and $wday has the range 0..6.  If EXPR is
  2616.           omitted, does localtime(time).
  2617. ╛KY log
  2618. ╛DT log(EXPR)
  2619. ╛C log(EXPR)
  2620. log EXPR
  2621.  
  2622.           Returns logarithm (base e) of EXPR.  If EXPR is omitted,
  2623.           returns log of $_.
  2624. ╛KY lstat
  2625. ╛DT lstat(FILEHANDLE)
  2626. ╛C lstat(FILEHANDLE)
  2627. lstat FILEHANDLE
  2628. lstat(EXPR)
  2629. lstat SCALARVARIABLE
  2630.  
  2631.           Does the same thing as the stat() function, but stats a
  2632.           symbolic link instead of the file the symbolic link
  2633.           points to.  If symbolic links are unimplemented on your
  2634.           system, a normal stat is done.
  2635. ╛KY m
  2636. ╛DT m/PATTERN/gio
  2637. ╛C m/PATTERN/gio
  2638. /PATTERN/gio
  2639.  
  2640.           Searches a string for a pattern match, and returns true
  2641.           (1) or false ('').  If no string is specified via the =~
  2642.           or !~ operator, the $_ string is searched.  (The string
  2643.           specified with =~ need not be an lvalue--it may be the
  2644.           result of an expression evaluation, but remember the =~
  2645.           binds rather tightly.) See also the section on regular
  2646.           expressions.
  2647.  
  2648.           If / is the delimiter then the initial 'm' is optional.
  2649.           With the 'm' you can use any pair of non-alphanumeric
  2650.           characters as delimiters.  This is particularly useful
  2651.           for matching Unix path names that contain '/'.  If the
  2652.           final delimiter is followed by the optional letter 'i',
  2653.           the matching is done in a case-insensitive manner.  PAT-
  2654.           TERN may contain references to scalar variables, which
  2655.           will be interpolated (and the pattern recompiled) every
  2656.           time the pattern search is evaluated.  (Note that $) and
  2657.           $| may not be interpolated because they look like end-
  2658.           of-string tests.) If you want such a pattern to be com-
  2659.           piled only once, add an "o" after the trailing delimiter.
  2660.           This avoids expensive run-time recompilations, and is
  2661.           useful when the value you are interpolating won't change
  2662.           over the life of the script.  If the PATTERN evaluates to
  2663.           a null string, the most recent successful regular expres-
  2664.           sion is used instead.
  2665.  
  2666.           If used in a context that requires an array value, a pat-
  2667.           tern match returns an array consisting of the subexpres-
  2668.           sions matched by the parentheses in the pattern, i.e.
  2669.           ($1, $2, $3...).  It does NOT actually set $1, $2, etc.
  2670.           in this case, nor does it set $+, $`, $& or $'.  If the
  2671.           match fails, a null array is returned.  If the match
  2672.           succeeds, but there were no parentheses, an array value
  2673.           of (1) is returned.
  2674.  
  2675.           Examples:
  2676.  
  2677.                     open(tty, '/dev/tty');
  2678.                     <tty> =~ /^y/i && do foo();    # do foo if desired
  2679.  
  2680.                     if (/Version: *([0-9.]*)/) { $version = $1; }
  2681.  
  2682.                     next if m#^/usr/spool/uucp#;
  2683.  
  2684.                     # poor man's grep
  2685.                     $arg = shift;
  2686.                     while (<>) {
  2687.                          print if /$arg/o;    # compile only once
  2688.                     }
  2689.  
  2690.                     if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
  2691.  
  2692.           This last example splits $foo into the first two words
  2693.           and the remainder of the line, and assigns those three
  2694.           fields to $F1, $F2 and $Etc.  The conditional is true if
  2695.           any variables were assigned, i.e. if the pattern matched.
  2696.  
  2697.           The g modifier specifies global pattern matching ╤ that is,
  2698.           matching as many times as possible within the string.  How 
  2699.           it behaves depends on the context.  In an array context, it 
  2700.           returns a list of all the substrings matched by all the 
  2701.           parentheses in the regular expression. If there are no 
  2702.           parentheses, it returns a list of all the matched strings,
  2703.           as if there were parentheses around the whole pattern.  In 
  2704.           a scalar context, it iterates through the string, returning 
  2705.           TRUE each time it matches, and FALSE when it eventually runs 
  2706.           out of matches.  (In other words, it remembers where it left 
  2707.           off last time and restarts the search at that point.)  It
  2708.           presumes that you have not modified the string since the last 
  2709.           match. Modifying the string between matches may result in 
  2710.           undefined behavior. (You can actually get away with in-place
  2711.           modifications via substr() that do not change the length of 
  2712.           the entire string.  In general, however, you should be using 
  2713.           s///g for such modifications.)  Examples:
  2714.  
  2715.                     # array context
  2716.                     ($one,$five,$fifteen) = (\`uptime\` =~ /(\ed+\e.\ed+)/g);
  2717.         
  2718.                     # scalar context
  2719.                     $/ = 1; $* = 1;
  2720.                     while ($paragraph = <>) {
  2721.                         while ($paragraph =~ /[a-z][\'")]*[.!?]+[\'")]*\es/g) {
  2722.                             $sentences++;
  2723.                         }
  2724.                     }
  2725.                     print "$sentences\en";
  2726.  
  2727. ?PATTERN?
  2728.  
  2729.           This is just like the /pattern/ search, except that it
  2730.           matches only once between calls to the reset operator.
  2731.           This is a useful optimization when you only want to see
  2732.           the first occurrence of something in each file of a set
  2733.           of files, for instance.  Only ?? patterns local to the
  2734.           current package are reset.
  2735. ╛KY mkdir
  2736. ╛DT mkdir(FILENAME,MODE)
  2737. ╛C mkdir(FILENAME,MODE)
  2738.  
  2739.           Creates the directory specified by FILENAME, with permis-
  2740.           sions specified by MODE (as modified by umask).  If it
  2741.           succeeds it returns 1, otherwise it returns 0 and sets $!
  2742.           (errno).
  2743. ╛KY msgctl
  2744. ╛DT msgctl(ID,CMD,ARG)
  2745. ╛C msgctl(ID,CMD,ARG)
  2746.  
  2747.           Calls the System V IPC function msgctl.  If CMD is
  2748.           &IPC_STAT, then ARG must be a variable which will hold
  2749.           the returned msqid_ds structure.  Returns like ioctl: the
  2750.           undefined value for error, "0 but true" for zero, or the
  2751.           actual return value otherwise.
  2752. ╛KY msgget
  2753. ╛DT msgget(KEY,FLAGS)
  2754. ╛C msgget(KEY,FLAGS)
  2755.  
  2756.           Calls the System V IPC function msgget.  Returns the mes-
  2757.           sage queue id, or the undefined value if there is an
  2758.           error.
  2759. ╛KY msgsnd
  2760. ╛DT msgsnd(ID,MSG,FLAGS)
  2761. ╛C msgsnd(ID,MSG,FLAGS)
  2762.  
  2763.           Calls the System V IPC function msgsnd to send the mes-
  2764.           sage MSG to the message queue ID.  MSG must begin with
  2765.           the long integer message type, which may be created with
  2766.           pack("L", $type).  Returns true if successful, or false
  2767.           if there is an error.
  2768. ╛KY msgrcv
  2769. ╛DT msgrcv(ID,VAR,SIZE,TYPE,FLAGS)
  2770. ╛C msgrcv(ID,VAR,SIZE,TYPE,FLAGS)
  2771.  
  2772.           Calls the System V IPC function msgrcv to receive a mes-
  2773.           sage from message queue ID into variable VAR with a max-
  2774.           imum message size of SIZE.  Note that if a message is
  2775.           received, the message type will be the first thing in
  2776.           VAR, and the maximum length of VAR is SIZE plus the size
  2777.           of the message type.  Returns true if successful, or
  2778.           false if there is an error.
  2779. ╛KY next
  2780. ╛DT next LABEL
  2781. ╛C next LABEL
  2782. next
  2783.           The next command is like the continue statement in C; it
  2784.           starts the next iteration of the loop:
  2785.  
  2786.                          line: while (<STDIN>) {
  2787.                               next line if /^#/;  # discard comments
  2788.                               ...
  2789.                          }
  2790.  
  2791.           Note that if there were a continue block on the above, it
  2792.           would get executed even on discarded lines.  If the LABEL
  2793.           is omitted, the command refers to the innermost enclosing
  2794.           loop.
  2795. ╛KY oct
  2796. ╛DT oct(EXPR)
  2797. ╛C oct(EXPR)
  2798. oct EXPR
  2799.  
  2800.           Returns the decimal value of EXPR interpreted as an octal
  2801.           string.  (If EXPR happens to start off with 0x, inter-
  2802.           prets it as a hex string instead.) The following will
  2803.           handle decimal, octal and hex in the standard notation:
  2804.  
  2805.                          $val = oct($val) if $val =~ /^0/;
  2806.  
  2807.           If EXPR is omitted, uses $_.
  2808. ╛KY open
  2809. ╛DT open(FILEHANDLE,EXPR)
  2810. ╛C open(FILEHANDLE,EXPR)
  2811. open(FILEHANDLE)
  2812. open FILEHANDLE
  2813.  
  2814.           Opens the file whose filename is given by EXPR, and asso-
  2815.           ciates it with FILEHANDLE.  If FILEHANDLE is an expres-
  2816.           sion, its value is used as the name of the real filehan-
  2817.           dle wanted.  If EXPR is omitted, the scalar variable of
  2818.           the same name as the FILEHANDLE contains the filename.
  2819.           If the filename begins with "<" or nothing, the file is
  2820.           opened for input.  If the filename begins with ">", the
  2821.           file is opened for output.  If the filename begins with
  2822.           ">>", the file is opened for appending.  (You can put a
  2823.           '+' in front of the '>' or '<' to indicate that you want
  2824.           both read and write access to the file.) If the filename
  2825.           begins with "|", the filename is interpreted as a command
  2826.           to which output is to be piped, and if the filename ends
  2827.           with a "|", the filename is interpreted as command which
  2828.           pipes input to us.  (You may not have a command that
  2829.           pipes both in and out.) Opening '-' opens STDIN and open-
  2830.           ing '>-' opens STDOUT.  Open returns non-zero upon suc-
  2831.           cess, the undefined value otherwise.  If the open
  2832.           involved a pipe, the return value happens to be the pid
  2833.           of the subprocess.  Examples:
  2834.  
  2835.                          $article = 100;
  2836.                          open article || die "Can't find article $article: $!\n";
  2837.                          while (<article>) {...
  2838.  
  2839.                          open(LOG, '>>/usr/spool/news/twitlog');
  2840.                                                        # (log is reserved)
  2841.  
  2842.                          open(article, "caesar <$article |");
  2843.                                                        # decrypt article
  2844.  
  2845.                          open(extract, "|sort >/tmp/Tmp$$");
  2846.                                                        # $$ is our process#
  2847.  
  2848.                          # process argument list of files along with any includes
  2849.  
  2850.                          foreach $file (@ARGV) {
  2851.                               do process($file, 'fh00');    # no pun intended
  2852.                          }
  2853.  
  2854.                          sub process {
  2855.                               local($filename, $input) = @_;
  2856.                               $input++;      # this is a string increment
  2857.                               unless (open($input, $filename)) {
  2858.                                    print STDERR "Can't open $filename: $!\n";
  2859.                                    return;
  2860.                               }
  2861.                               while (<$input>) {       # note use of indirection
  2862.                                    if (/^#include "(.*)"/) {
  2863.                                                   do process($1, $input);
  2864.                                                   next;
  2865.                                    }
  2866.                                    ...       # whatever
  2867.                               }
  2868.                          }
  2869.  
  2870.           You may also, in the Bourne shell tradition, specify an
  2871.           EXPR beginning with ">&", in which case the rest of the
  2872.           string is interpreted as the name of a filehandle (or
  2873.           file descriptor, if numeric) which is to be duped and
  2874.           opened.  You may use & after >, >>, <, +>, +>> and +<.
  2875.           The mode you specify should match the mode of the origi-
  2876.           nal filehandle.  Here is a script that saves, redirects,
  2877.           and restores STDOUT and STDERR:
  2878.  
  2879.                          #!/usr/bin/perl
  2880.                          open(SAVEOUT, ">&STDOUT");
  2881.                          open(SAVEERR, ">&STDERR");
  2882.  
  2883.                          open(STDOUT, ">foo.out") || die "Can't redirect stdout";
  2884.                          open(STDERR, ">&STDOUT") || die "Can't dup stdout";
  2885.  
  2886.                          select(STDERR); $| = 1;       # make unbuffered
  2887.                          select(STDOUT); $| = 1;       # make unbuffered
  2888.  
  2889.                          print STDOUT "stdout 1\n";    # this works for
  2890.                          print STDERR "stderr 1\n";    # subprocesses too
  2891.  
  2892.                          close(STDOUT);
  2893.                          close(STDERR);
  2894.  
  2895.                          open(STDOUT, ">&SAVEOUT");
  2896.                          open(STDERR, ">&SAVEERR");
  2897.  
  2898.                          print STDOUT "stdout 2\n";
  2899.                          print STDERR "stderr 2\n";
  2900.  
  2901.           If you open a pipe on the command "-", i.e. either "|-"
  2902.           or "-|", then there is an implicit fork done, and the
  2903.           return value of open is the pid of the child within the
  2904.           parent process, and 0 within the child process.  (Use
  2905.           defined($pid) to determine if the open was successful.)
  2906.           The filehandle behaves normally for the parent, but i/o
  2907.           to that filehandle is piped from/to the STDOUT/STDIN of
  2908.           the child process.  In the child process the filehandle
  2909.           isn't opened--i/o happens from/to the new STDOUT or
  2910.           STDIN.  Typically this is used like the normal piped open
  2911.           when you want to exercise more control over just how the
  2912.           pipe command gets executed, such as when you are running
  2913.           setuid, and don't want to have to scan shell commands for
  2914.           metacharacters.  The following pairs are more or less
  2915.           equivalent:
  2916.  
  2917.                          open(FOO, "|tr '[a-z]' '[A-Z]'");
  2918.                          open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
  2919.  
  2920.                          open(FOO, "cat -n '$file'|");
  2921.                          open(FOO, "-|") || exec 'cat', '-n', $file;
  2922.  
  2923.           Explicitly closing any piped filehandle causes the parent
  2924.           process to wait for the child to finish, and returns the
  2925.           status value in $?.  Note: on any operation which may do
  2926.           a fork, unflushed buffers remain unflushed in both
  2927.           processes, which means you may need to set $| to avoid
  2928.           duplicate output.
  2929.  
  2930.           The filename that is passed to open will have leading and
  2931.           trailing whitespace deleted.  In order to open a file
  2932.           with arbitrary weird characters in it, it's necessary to
  2933.           protect any leading and trailing whitespace thusly:
  2934.  
  2935.                               $file =~ s#^(\s)#./$1#;
  2936.                               open(FOO, "< $file\0");
  2937. ╛KY opendir
  2938. ╛DT opendir(DIRHANDLE,EXPR)
  2939. ╛C opendir(DIRHANDLE,EXPR)
  2940.  
  2941.           Opens a directory named EXPR for processing by readdir(),
  2942.           telldir(), seekdir(), rewinddir() and closedir().
  2943.           Returns true if successful.  DIRHANDLEs have their own
  2944.           namespace separate from FILEHANDLEs.
  2945. ╛KY ord
  2946. ╛DT ord(EXPR)
  2947. ╛C ord(EXPR)
  2948. ord EXPR
  2949.  
  2950.           Returns the numeric ascii value of the first character of
  2951.           EXPR.  If EXPR is omitted, uses $_.
  2952. ╛KY pack
  2953. ╛DT pack(TEMPLATE,LIST)
  2954. ╛C pack(TEMPLATE,LIST)
  2955.  
  2956.           Takes an array or list of values and packs it into a
  2957.           binary structure, returning the string containing the
  2958.           structure.  The TEMPLATE is a sequence of characters that
  2959.           give the order and type of values, as follows:
  2960.  
  2961.                          A    An ascii string, will be space padded.
  2962.                          a    An ascii string, will be null padded.
  2963.                          c    A signed char value.
  2964.                          C    An unsigned char value.
  2965.                          s    A signed short value.
  2966.                          S    An unsigned short value.
  2967.                          i    A signed integer value.
  2968.                          I    An unsigned integer value.
  2969.                          l    A signed long value.
  2970.                          L    An unsigned long value.
  2971.                          n    A short in "network" order.
  2972.                          N    A long in "network" order.
  2973.                          v      A short in VAX (little-endian) order.
  2974.                          V      A long in VAX (little-endian) order.
  2975.                          f    A single-precision float in the native format.
  2976.                          d    A double-precision float in the native format.
  2977.                          p    A pointer to a string.
  2978.                          x    A null byte.
  2979.                          X    Back up a byte.
  2980.                          @    Null fill to absolute position.
  2981.                          u    A uuencoded string.
  2982.                          b    A bit string (ascending bit order, like vec()).
  2983.                          B    A bit string (descending bit order).
  2984.                          h    A hex string (low nybble first).
  2985.                          H    A hex string (high nybble first).
  2986.  
  2987.           Each letter may optionally be followed by a number which
  2988.           gives a repeat count.  With all types except "a", "A",
  2989.           "b", "B", "h" and "H", the pack function will gobble up
  2990.           that many values from the LIST.  A * for the repeat count
  2991.           means to use however many items are left.  The "a" and
  2992.           "A" types gobble just one value, but pack it as a string
  2993.           of length count, padding with nulls or spaces as neces-
  2994.           sary.  (When unpacking, "A" strips trailing spaces and
  2995.           nulls, but "a" does not.) Likewise, the "b" and "B"
  2996.           fields pack a string that many bits long.  The "h" and
  2997.           "H" fields pack a string that many nybbles long.  Real
  2998.           numbers (floats and doubles) are in the native machine
  2999.           format only; due to the multiplicity of floating formats
  3000.           around, and the lack of a standard "network" representa-
  3001.           tion, no facility for interchange has been made.  This
  3002.           means that packed floating point data written on one
  3003.           machine may not be readable on another - even if both use
  3004.           IEEE floating point arithmetic (as the endian-ness of the
  3005.           memory representation is not part of the IEEE spec).
  3006.           Note that perl uses doubles internally for all numeric
  3007.           calculation, and converting from double -> float -> dou-
  3008.           ble will lose precision (i.e. unpack("f", pack("f",
  3009.           $foo)) will not in general equal $foo).
  3010.           Examples:
  3011.  
  3012.                          $foo = pack("cccc",65,66,67,68);
  3013.                          # foo eq "ABCD"
  3014.                          $foo = pack("c4",65,66,67,68);
  3015.                          # same thing
  3016.  
  3017.                          $foo = pack("ccxxcc",65,66,67,68);
  3018.                          # foo eq "AB\0\0CD"
  3019.  
  3020.                          $foo = pack("s2",1,2);
  3021.                          # "\1\0\2\0" on little-endian
  3022.                          # "\0\1\0\2" on big-endian
  3023.  
  3024.                          $foo = pack("a4","abcd","x","y","z");
  3025.                          # "abcd"
  3026.  
  3027.                          $foo = pack("aaaa","abcd","x","y","z");
  3028.                          # "axyz"
  3029.  
  3030.                          $foo = pack("a14","abcdefg");
  3031.                          # "abcdefg\0\0\0\0\0\0\0"
  3032.  
  3033.                          $foo = pack("i9pl", gmtime);
  3034.                          # a real struct tm (on my system anyway)
  3035.  
  3036.                          sub bintodec {
  3037.                          unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  3038.                          }
  3039.           The same template may generally also be used in the
  3040.           unpack function.
  3041. ╛KY pipe
  3042. ╛DT pipe(READHANDLE,WRITEHANDLE)
  3043. ╛C pipe(READHANDLE,WRITEHANDLE)
  3044.  
  3045.           Opens a pair of connected pipes like the corresponding
  3046.           system call.  Note that if you set up a loop of piped
  3047.           processes, deadlock can occur unless you are very care-
  3048.           ful.  In addition, note that perl's pipes use stdio
  3049.           buffering, so you may need to set $| to flush your WRI-
  3050.           TEHANDLE after each command, depending on the applica-
  3051.           tion.  [Requires version 3.0 patchlevel 9.]
  3052. ╛KY pop
  3053. ╛DT pop(ARRAY)
  3054. ╛C pop(ARRAY)
  3055. pop ARRAY
  3056.  
  3057.           Pops and returns the last value of the array, shortening
  3058.           the array by 1.  Has the same effect as
  3059.  
  3060.                          $tmp = $ARRAY[$#ARRAY--];
  3061.  
  3062.           If there are no elements in the array, returns the unde-
  3063.           fined value.
  3064. ╛KY print
  3065. ╛DT print(FILEHANDLE LIST)
  3066. ╛C print(FILEHANDLE LIST)
  3067. print(LIST)
  3068. print FILEHANDLE LIST
  3069. print LIST
  3070. print
  3071.           Prints a string or a comma-separated list of strings.
  3072.           Returns non-zero if successful.  FILEHANDLE may be a
  3073.           scalar variable name, in which case the variable contains
  3074.           the name of the filehandle, thus introducing one level of
  3075.           indirection.  (NOTE: If FILEHANDLE is a variable and the
  3076.           next token is a term, it may be misinterpreted as an
  3077.           operator unless you interpose a + or put parens around
  3078.           the arguments.) If FILEHANDLE is omitted, prints by
  3079.           default to standard output (or to the last selected out-
  3080.           put channel--see select()).  If LIST is also omitted,
  3081.           prints $_ to STDOUT.  To set the default output channel
  3082.           to something other than STDOUT use the select operation.
  3083.           Note that, because print takes a LIST, anything in the
  3084.           LIST is evaluated in an array context, and any subroutine
  3085.           that you call will have one or more of its expressions
  3086.           evaluated in an array context.  Also be careful not to
  3087.           follow the print keyword with a left parenthesis unless
  3088.           you want the corresponding right parenthesis to terminate
  3089.           the arguments to the print--interpose a + or put parens
  3090.           around all the arguments.
  3091. ╛KY printf
  3092. ╛DT printf(FILEHANDLE LIST)
  3093. ╛C printf(FILEHANDLE LIST)
  3094. printf(LIST)
  3095. printf FILEHANDLE LIST
  3096. printf LIST
  3097.  
  3098.           Equivalent to a "print FILEHANDLE sprintf(LIST)".
  3099. ╛KY push
  3100. ╛DT push(ARRAY,LIST)
  3101. ╛C push(ARRAY,LIST)
  3102.  
  3103.           Treats ARRAY (@ is optional) as a stack, and pushes the
  3104.           values of LIST onto the end of ARRAY.  The length of
  3105.           ARRAY increases by the length of LIST.  Has the same
  3106.           effect as
  3107.  
  3108.                     for $value (LIST) {
  3109.                          $ARRAY[++$#ARRAY] = $value;
  3110.                     }
  3111.  
  3112.           but is more efficient.
  3113. ╛KY q
  3114. ╛DT q/STRING/
  3115. ╛C q/STRING/
  3116. qq/STRING/
  3117. qx/STRING/
  3118.  
  3119.           These are not really functions, but simply syntactic
  3120.           sugar to let you avoid putting too many backslashes into
  3121.           quoted strings.  The q operator is a generalized single
  3122.           quote, and the qq operator a generalized double quote.
  3123.           The qx operator is a generalized backquote.  Any non-
  3124.           alphanumeric delimiter can be used in place of /, includ-
  3125.           ing newline.  If the delimiter is an opening bracket or
  3126.           parenthesis, the final delimiter will be the correspond-
  3127.           ing closing bracket or parenthesis.  (Embedded
  3128.           occurrences of the closing bracket need to be backslashed
  3129.           as usual.) Examples:
  3130.  
  3131.                          $foo = q!I said, "You said, 'She said it.'"!;
  3132.                          $bar = q('This is it.');
  3133.                          $today = qx{ date };
  3134.                          $_ .= qq
  3135.           *** The previous line contains the naughty word "$&".\n
  3136.                               if /(ibm|apple|awk)/;      # :-)
  3137. ╛KY rand
  3138. ╛DT rand(EXPR)
  3139. ╛C rand(EXPR)
  3140. rand EXPR
  3141. rand
  3142.           Returns a random fractional number between 0 and the
  3143.           value of EXPR.  (EXPR should be positive.) If EXPR is
  3144.           omitted, returns a value between 0 and 1.  See also
  3145.           srand().
  3146. ╛KY read
  3147. ╛DT read(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3148. ╛C read(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3149. read(FILEHANDLE,SCALAR,LENGTH)
  3150.  
  3151.           Attempts to read LENGTH bytes of data into variable
  3152.           SCALAR from the specified FILEHANDLE.  Returns the number
  3153.           of bytes actually read, or undef if there was an error.
  3154.           SCALAR will be grown or shrunk to the length actually
  3155.           read.  An OFFSET may be specified to place the read data
  3156.           at some other place than the beginning of the string.
  3157.           This call is actually implemented in terms of stdio's
  3158.           fread call.  To get a true read system call, see sysread.
  3159. ╛KY readdir
  3160. ╛DT readdir(DIRHANDLE)
  3161. ╛C readdir(DIRHANDLE)
  3162. readdir DIRHANDLE
  3163.  
  3164.           Returns the next directory entry for a directory opened
  3165.           by opendir().  If used in an array context, returns all
  3166.           the rest of the entries in the directory.  If there are
  3167.           no more entries, returns an undefined value in a scalar
  3168.           context or a null list in an array context.
  3169. ╛KY readlink
  3170. ╛DT readlink(EXPR)
  3171. ╛C readlink(EXPR)
  3172. readlink EXPR
  3173.  
  3174.           Returns the value of a symbolic link, if symbolic links
  3175.           are implemented.  If not, gives a fatal error.  If there
  3176.           is some system error, returns the undefined value and
  3177.           sets $! (errno).  If EXPR is omitted, uses $_.
  3178. ╛KY recv
  3179. ╛DT recv(SOCKET,SCALAR,LEN,FLAGS)
  3180. ╛C recv(SOCKET,SCALAR,LEN,FLAGS)
  3181.  
  3182.           Receives a message on a socket.  Attempts to receive
  3183.           LENGTH bytes of data into variable SCALAR from the speci-
  3184.           fied SOCKET filehandle.  Returns the address of the
  3185.           sender, or the undefined value if there's an error.
  3186.           SCALAR will be grown or shrunk to the length actually
  3187.           read.  Takes the same flags as the system call of the
  3188.           same name.
  3189. ╛KY redo
  3190. ╛DT redo LABEL
  3191. ╛C redo LABEL
  3192. redo
  3193.           The redo command restarts the loop block without evaluat-
  3194.           ing the conditional again.  The continue block, if any,
  3195.           is not executed.  If the LABEL is omitted, the command
  3196.           refers to the innermost enclosing loop.  This command is
  3197.           normally used by programs that want to lie to themselves
  3198.           about what was just input:
  3199.  
  3200.                          # a simpleminded Pascal comment stripper
  3201.                          # (warning: assumes no { or } in strings)
  3202.                          line: while (<STDIN>) {
  3203.                               while (s|({.*}.*){.*}|$1 |) {}
  3204.                               s|{.*}| |;
  3205.                               if (s|{.*| |) {
  3206.                                    $front = $_;
  3207.                                    while (<STDIN>) {
  3208.                                                   if (/}/) {     # end of comment?
  3209.                                                        s|^|$front{|;
  3210.                                                        redo line;
  3211.                                                   }
  3212.                                    }
  3213.                               }
  3214.                               print;
  3215.                          }
  3216. ╛KY rename
  3217. ╛DT rename(OLDNAME,NEWNAME)
  3218. ╛C rename(OLDNAME,NEWNAME)
  3219.  
  3220.           Changes the name of a file.  Returns 1 for success, 0
  3221.           otherwise.  Will not work across filesystem boundaries.
  3222. ╛KY require
  3223. ╛DT require(EXPR)
  3224. ╛C require(EXPR)
  3225. require EXPR
  3226. require
  3227.           Includes the library file specified by EXPR, or by $_ if
  3228.           EXPR is not supplied.  Has semantics similar to the fol-
  3229.           lowing subroutine:
  3230.  
  3231.                          sub require {
  3232.                          local($filename) = @_;
  3233.                          return 1 if $INC{$filename};
  3234.                          local($realfilename,$result);
  3235.                          ITER: {
  3236.                               foreach $prefix (@INC) {
  3237.                                         $realfilename = "$prefix/$filename";
  3238.                                         if (-f $realfilename) {
  3239.                                    $result = do $realfilename;
  3240.                                    last ITER;
  3241.                                         }
  3242.                               }
  3243.                               die "Can't find $filename in \@INC";
  3244.                          }
  3245.                          die $@ if $@;
  3246.                          die "$filename did not return true value" unless $result;
  3247.                          $INC{$filename} = $realfilename;
  3248.                          $result;
  3249.                          }
  3250.  
  3251.           Note that the file will not be included twice under the
  3252.           same specified name.
  3253. ╛KY reset
  3254. ╛DT reset(EXPR)
  3255. ╛C reset(EXPR)
  3256. reset EXPR
  3257. reset
  3258.           Generally used in a continue block at the end of a loop
  3259.           to clear variables and reset ?? searches so that they
  3260.           work again.  The expression is interpreted as a list of
  3261.           single characters (hyphens allowed for ranges).  All
  3262.           variables and arrays beginning with one of those letters
  3263.           are reset to their pristine state.  If the expression is
  3264.           omitted, one-match searches (?pattern?) are reset to
  3265.           match again.  Only resets variables or searches in the
  3266.           current package.  Always returns 1.  Examples:
  3267.  
  3268.                     reset 'X';      # reset all X variables
  3269.                     reset 'a-z';    # reset lower case variables
  3270.                     reset;          # just reset ?? searches
  3271.  
  3272.           Note: resetting "A-Z" is not recommended since you'll
  3273.           wipe out your ARGV and ENV arrays.
  3274.  
  3275.           The use of reset on dbm associative arrays does not
  3276.           change the dbm file.  (It does, however, flush any
  3277.           entries cached by perl, which may be useful if you are
  3278.           sharing the dbm file.  Then again, maybe not.)
  3279. ╛KY return
  3280. ╛DT return LIST
  3281. ╛C return LIST
  3282.  
  3283.           Returns from a subroutine with the value specified.
  3284.           (Note that a subroutine can automatically return the
  3285.           value of the last expression evaluated.  That's the pre-
  3286.           ferred method--use of an explicit return is a bit
  3287.           slower.)
  3288. ╛KY reverse
  3289. ╛DT reverse(LIST)
  3290. ╛C reverse(LIST)
  3291. reverse LIST
  3292.  
  3293.           In an array context, returns an array value consisting of
  3294.           the elements of LIST in the opposite order.  In a scalar
  3295.           context, returns a string value consisting of the bytes
  3296.           of the first element of LIST in the opposite order.
  3297. ╛KY rewinddir
  3298. ╛DT rewinddir(DIRHANDLE)
  3299. ╛C rewinddir(DIRHANDLE)
  3300. rewinddir DIRHANDLE
  3301.  
  3302.           Sets the current position to the beginning of the direc-
  3303.           tory for the readdir() routine on DIRHANDLE.
  3304. ╛KY rindex
  3305. ╛DT rindex(STR,SUBSTR,POSITION)
  3306. ╛C rindex(STR,SUBSTR,POSITION)
  3307. rindex(STR,SUBSTR)
  3308.  
  3309.           Works just like index except that it returns the position
  3310.           of the LAST occurrence of SUBSTR in STR.  If POSITION is
  3311.           specified, returns the last occurrence at or before that
  3312.           position.
  3313. ╛KY rmdir
  3314. ╛DT rmdir(FILENAME)
  3315. ╛C rmdir(FILENAME)
  3316. rmdir FILENAME
  3317.  
  3318.           Deletes the directory specified by FILENAME if it is
  3319.           empty.  If it succeeds it returns 1, otherwise it returns
  3320.           0 and sets $! (errno).  If FILENAME is omitted, uses $_.
  3321. ╛KY s
  3322. ╛DT s/PATTERN/REPLACEMENT/gieo
  3323. ╛C s/PATTERN/REPLACEMENT/gieo
  3324.  
  3325.           Searches a string for a pattern, and if found, replaces
  3326.           that pattern with the replacement text and returns the
  3327.           number of substitutions made.  Otherwise it returns false
  3328.           (0).  The "g" is optional, and if present, indicates that
  3329.           all occurrences of the pattern are to be replaced.  The
  3330.           "i" is also optional, and if present, indicates that
  3331.           matching is to be done in a case-insensitive manner.  The
  3332.           "e" is likewise optional, and if present, indicates that
  3333.           the replacement string is to be evaluated as an expres-
  3334.           sion rather than just as a double-quoted string.  Any
  3335.           non-alphanumeric delimiter may replace the slashes; if
  3336.           single quotes are used, no interpretation is done on the
  3337.           replacement string (the e modifier overrides this, how-
  3338.           ever); if backquotes are used, the replacement string is
  3339.           a command to execute whose output will be used as the
  3340.           actual replacement text.  If no string is specified via
  3341.           the =~ or !~ operator, the $_ string is searched and
  3342.           modified.  (The string specified with =~ must be a scalar
  3343.           variable, an array element, or an assignment to one of
  3344.           those, i.e. an lvalue.) If the pattern contains a $ that
  3345.           looks like a variable rather than an end-of-string test,
  3346.           the variable will be interpolated into the pattern at
  3347.           run-time.  If you only want the pattern compiled once the
  3348.           first time the variable is interpolated, add an "o" at
  3349.           the end.  If the PATTERN evaluates to a null string, the
  3350.           most recent successful regular expression is used
  3351.           instead.  See also the section on regular expressions.
  3352.           Examples:
  3353.  
  3354.                     s/\bgreen\b/mauve/g;      # don't change wintergreen
  3355.  
  3356.                     $path =~ s|/usr/bin|/usr/local/bin|;
  3357.  
  3358.                     s/Login: $foo/Login: $bar/; # run-time pattern
  3359.  
  3360.                     ($foo = $bar) =~ s/bar/foo/;
  3361.  
  3362.                     $_ = 'abc123xyz';
  3363.                     s/\d+/$&*2/e;        # yields 'abc246xyz'
  3364.                     s/\d+/sprintf("%5d",$&)/e;     # yields 'abc  246xyz'
  3365.                     s/\w/$& x 2/eg;      # yields 'aabbcc  224466xxyyzz'
  3366.  
  3367.                     s/([^ ]*) *([^ ]*)/$2 $1/;     # reverse 1st two fields
  3368.  
  3369.           (Note the use of $ instead of \ in the last example.  See
  3370.           section on regular expressions.)
  3371. ╛KY scalar
  3372. ╛DT scalar(EXPR)
  3373. ╛C scalar(EXPR)
  3374.  
  3375.           Forces EXPR to be interpreted in a scalar context and
  3376.           returns the value of EXPR.
  3377. ╛KY seek
  3378. ╛DT seek(FILEHANDLE,POSITION,WHENCE)
  3379. ╛C seek(FILEHANDLE,POSITION,WHENCE)
  3380.  
  3381.           Randomly positions the file pointer for FILEHANDLE, just
  3382.           like the fseek() call of stdio.  FILEHANDLE may be an
  3383.           expression whose value gives the name of the filehandle.
  3384.           Returns 1 upon success, 0 otherwise.
  3385. ╛KY seekdir
  3386. ╛DT seekdir(DIRHANDLE,POS)
  3387. ╛C seekdir(DIRHANDLE,POS)
  3388.  
  3389.           Sets the current position for the readdir() routine on
  3390.           DIRHANDLE.  POS must be a value returned by telldir().
  3391.           Has the same caveats about possible directory compaction
  3392.           as the corresponding system library routine.
  3393. ╛KY select
  3394. ╛DT select(FILEHANDLE)
  3395. ╛C select(FILEHANDLE)
  3396. select
  3397.           Returns the currently selected filehandle.  Sets the
  3398.           current default filehandle for output, if FILEHANDLE is
  3399.           supplied.  This has two effects: first, a write or a
  3400.           print without a filehandle will default to this FILEHAN-
  3401.           DLE.  Second, references to variables related to output
  3402.           will refer to this output channel.  For example, if you
  3403.           have to set the top of form format for more than one out-
  3404.           put channel, you might do the following:
  3405.  
  3406.                          select(REPORT1);
  3407.                          $^ = 'report1_top';
  3408.                          select(REPORT2);
  3409.                          $^ = 'report2_top';
  3410.  
  3411.           FILEHANDLE may be an expression whose value gives the
  3412.           name of the actual filehandle.  Thus:
  3413.  
  3414.                          $oldfh = select(STDERR); $| = 1; select($oldfh);
  3415.  
  3416. select(RBITS,WBITS,EBITS,TIMEOUT)
  3417.  
  3418.           This calls the select system call with the bitmasks
  3419.           specified, which can be constructed using fileno() and
  3420.           vec(), along these lines:
  3421.  
  3422.                          $rin = $win = $ein = '';
  3423.                          vec($rin,fileno(STDIN),1) = 1;
  3424.                          vec($win,fileno(STDOUT),1) = 1;
  3425.                          $ein = $rin | $win;
  3426.  
  3427.           If you want to select on many filehandles you might wish
  3428.           to write a subroutine:
  3429.  
  3430.                          sub fhbits {
  3431.                          local(@fhlist) = split(' ',$_[0]);
  3432.                          local($bits);
  3433.                          for (@fhlist) {
  3434.                               vec($bits,fileno($_),1) = 1;
  3435.                          }
  3436.                          $bits;
  3437.                          }
  3438.                          $rin = &fhbits('STDIN TTY SOCK');
  3439.  
  3440.           The usual idiom is:
  3441.  
  3442.                          ($nfound,$timeleft) =
  3443.                          select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  3444.  
  3445.           or to block until something becomes ready:
  3446.  
  3447.                          $nfound = select($rout=$rin, $wout=$win,
  3448.                                                   $eout=$ein, undef);
  3449.  
  3450.           Any of the bitmasks can also be undef.  The timeout, if
  3451.           specified, is in seconds, which may be fractional.  NOTE:
  3452.           not all implementations are capable of returning the
  3453.           $timeleft.  If not, they always return $timeleft equal to
  3454.           the supplied $timeout.
  3455. ╛KY semctl
  3456. ╛DT semctl(ID,SEMNUM,CMD,ARG)
  3457. ╛C semctl(ID,SEMNUM,CMD,ARG)
  3458.  
  3459.           Calls the System V IPC function semctl.  If CMD is
  3460.           &IPC_STAT or &GETALL, then ARG must be a variable which
  3461.           will hold the returned semid_ds structure or semaphore
  3462.           value array.  Returns like ioctl: the undefined value for
  3463.           error, "0 but true" for zero, or the actual return value
  3464.           otherwise.
  3465. ╛KY semget
  3466. ╛DT semget(KEY,NSEMS,SIZE,FLAGS)
  3467. ╛C semget(KEY,NSEMS,SIZE,FLAGS)
  3468.  
  3469.           Calls the System V IPC function semget.  Returns the
  3470.           semaphore id, or the undefined value if there is an
  3471.           error.
  3472. ╛KY semop
  3473. ╛DT semop(KEY,OPSTRING)
  3474. ╛C semop(KEY,OPSTRING)
  3475.  
  3476.           Calls the System V IPC function semop to perform sema-
  3477.           phore operations such as signaling and waiting.  OPSTRING
  3478.           must be a packed array of semop structures.  Each semop
  3479.           structure can be generated with 'pack("sss", $semnum,
  3480.           $semop, $semflag)'.  The number of semaphore operations
  3481.           is implied by the length of OPSTRING.  Returns true if
  3482.           successful, or false if there is an error.  As an exam-
  3483.           ple, the following code waits on semaphore $semnum of
  3484.           semaphore id $semid:
  3485.  
  3486.                          $semop = pack("sss", $semnum, -1, 0);
  3487.                          die "Semaphore trouble: $!\n" unless semop($semid, $semop);
  3488.  
  3489.           To signal the semaphore, replace "-1" with "1".
  3490. ╛KY send
  3491. ╛DT send(SOCKET,MSG,FLAGS,TO)
  3492. ╛C send(SOCKET,MSG,FLAGS,TO)
  3493. send(SOCKET,MSG,FLAGS)
  3494.  
  3495.           Sends a message on a socket.  Takes the same flags as the
  3496.           system call of the same name.  On unconnected sockets you
  3497.           must specify a destination to send TO.  Returns the
  3498.           number of characters sent, or the undefined value if
  3499.           there is an error.
  3500. ╛KY setpgrp
  3501. ╛DT setpgrp(PID,PGRP)
  3502. ╛C setpgrp(PID,PGRP)
  3503.  
  3504.           Sets the current process group for the specified PID, 0
  3505.           for the current process.  Will produce a fatal error if
  3506.           used on a machine that doesn't implement setpgrp(2).
  3507. ╛KY setpriority
  3508. ╛DT setpriority(WHICH,WHO,PRIORITY)
  3509. ╛C setpriority(WHICH,WHO,PRIORITY)
  3510.  
  3511.           Sets the current priority for a process, a process group,
  3512.           or a user.  (See setpriority(2).) Will produce a fatal
  3513.           error if used on a machine that doesn't implement set-
  3514.           priority(2).
  3515. ╛KY setsockopt
  3516. ╛DT setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
  3517. ╛C setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
  3518.  
  3519.           Sets the socket option requested.  Returns undefined if
  3520.           there is an error.  OPTVAL may be specified as undef if
  3521.           you don't want to pass an argument.
  3522. ╛KY shift
  3523. ╛DT shift(ARRAY)
  3524. ╛C shift(ARRAY)
  3525. shift ARRAY
  3526. shift
  3527.           Shifts the first value of the array off and returns it,
  3528.           shortening the array by 1 and moving everything down.  If
  3529.           there are no elements in the array, returns the undefined
  3530.           value.  If ARRAY is omitted, shifts the @ARGV array in
  3531.           the main program, and the @_ array in subroutines.  (This
  3532.           is determined lexically.) See also unshift(), push() and
  3533.           pop().  Shift() and unshift() do the same thing to the
  3534.           left end of an array that push() and pop() do to the
  3535.           right end.
  3536. ╛KY shmctl
  3537. ╛DT shmctl(ID,CMD,ARG)
  3538. ╛C shmctl(ID,CMD,ARG)
  3539.  
  3540.           Calls the System V IPC function shmctl.  If CMD is
  3541.           &IPC_STAT, then ARG must be a variable which will hold
  3542.           the returned shmid_ds structure.  Returns like ioctl: the
  3543.           undefined value for error, "0 but true" for zero, or the
  3544.           actual return value otherwise.
  3545. ╛KY shmget
  3546. ╛DT shmget(KEY,SIZE,FLAGS)
  3547. ╛C shmget(KEY,SIZE,FLAGS)
  3548.  
  3549.           Calls the System V IPC function shmget.  Returns the
  3550.           shared memory segment id, or the undefined value if there
  3551.           is an error.
  3552. ╛KY shmread
  3553. ╛DT shmread(ID,VAR,POS,SIZE)
  3554. ╛C shmread(ID,VAR,POS,SIZE)
  3555. shmwrite(ID,STRING,POS,SIZE)
  3556.  
  3557.           Reads or writes the System V shared memory segment ID
  3558.           starting at position POS for size SIZE by attaching to
  3559.           it, copying in/out, and detaching from it.  When reading,
  3560.           VAR must be a variable which will hold the data read.
  3561.           When writing, if STRING is too long, only SIZE bytes are
  3562.           used; if STRING is too short, nulls are written to fill
  3563.           out SIZE bytes.  Return true if successful, or false if
  3564.           there is an error.
  3565. ╛KY shutdown
  3566. ╛DT shutdown(SOCKET,HOW)
  3567. ╛C shutdown(SOCKET,HOW)
  3568.  
  3569.           Shuts down a socket connection in the manner indicated by
  3570.           HOW, which has the same interpretation as in the system
  3571.           call of the same name.
  3572. ╛KY sin
  3573. ╛DT sin(EXPR)
  3574. ╛C sin(EXPR)
  3575. sin EXPR
  3576.  
  3577.           Returns the sine of EXPR (expressed in radians).  If EXPR
  3578.           is omitted, returns sine of $_.
  3579. ╛KY sleep
  3580. ╛DT sleep(EXPR)
  3581. ╛C sleep(EXPR)
  3582. sleep EXPR
  3583. sleep
  3584.           Causes the script to sleep for EXPR seconds, or forever
  3585.           if no EXPR.  May be interrupted by sending the process a
  3586.           SIGALRM.  Returns the number of seconds actually slept.
  3587.           You probably cannot mix alarm() and sleep() calls, since 
  3588.           sleep() is often implemented using alarm().
  3589. ╛KY socket
  3590. ╛DT socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
  3591. ╛C socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
  3592.  
  3593.           Opens a socket of the specified kind and attaches it to
  3594.           filehandle SOCKET.  DOMAIN, TYPE and PROTOCOL are speci-
  3595.           fied the same as for the system call of the same name.
  3596.           You may need to run h2ph on sys/socket.h to get the
  3597.           proper values handy in a perl library file.  Return true
  3598.           if successful.  See the example in the section on Inter-
  3599.           process Communication.
  3600. ╛KY socketpair
  3601. ╛DT socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
  3602. ╛C socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
  3603.  
  3604.           Creates an unnamed pair of sockets in the specified
  3605.           domain, of the specified type.  DOMAIN, TYPE and PROTOCOL
  3606.           are specified the same as for the system call of the same
  3607.           name.  If unimplemented, yields a fatal error.  Return
  3608.           true if successful.
  3609. ╛KY sort
  3610. ╛DT sort(SUBROUTINE LIST)
  3611. ╛C sort(SUBROUTINE LIST)
  3612. sort(LIST)
  3613. sort SUBROUTINE LIST
  3614. sort LIST
  3615.  
  3616.           Sorts the LIST and returns the sorted array value. Non-
  3617.           existent values of arrays are stripped out.  If SUBROUTINE 
  3618.           or BLOCK is omitted, sorts in standard string comparison
  3619.           order.  If SUBROUTINE is specified, gives the name of a
  3620.           subroutine that returns an integer less than, equal to,
  3621.           or greater than 0, depending on how the elements of the
  3622.           array are to be ordered.  In the interests of efficiency
  3623.           the normal calling code for subroutines is bypassed, with
  3624.           the following effects: the subroutine may not be a recur-
  3625.           sive subroutine, and the two elements to be compared are
  3626.           passed into the subroutine not via @_ but as $a and $b
  3627.           (see example below).  They are passed by reference so
  3628.           don't modify $a and $b.  (The <=> and cmp operators are 
  3629.           extremely useful in such routines.) SUBROUTINE may be a 
  3630.           scalar variable name, in which case the value provides
  3631.           the name of the subroutine to use.
  3632.           In place of a SUBROUTINE name, you can provide a BLOCK as 
  3633.           an anonymous, in-line sort subroutine. Examples:
  3634.  
  3635.                          # sort lexically
  3636.                          @articles = sort @files;
  3637.  
  3638.                          # same thing, but with explicit sort routine
  3639.                          @articles = sort {$a cmp $b;} @files;
  3640.  
  3641.                          # same thing in reversed order
  3642.                          @articles = sort {$b cmp $a;} @files;
  3643.  
  3644.                          # sort numerically ascending
  3645.                          @articles = sort {$a <=> $b;} @files;
  3646.  
  3647.                          # sort numerically descending
  3648.                          @articles = sort {$b <=> $a;} @files;
  3649.  
  3650.                          # sort using explicit subroutine name
  3651.                          sub byage {
  3652.                          $age{$a} <=> $age{$b}; # presuming integers
  3653.                          }
  3654.                          @sortedclass = sort byage @class;
  3655.  
  3656.                          sub reverse { $b cmp $a; }
  3657.                          @harry = ('dog','cat','x','Cain','Abel');
  3658.                          @george = ('gone','chased','yz','Punished','Axed');
  3659.                          print sort @harry;
  3660.                               # prints AbelCaincatdogx
  3661.                          print sort reverse @harry;
  3662.                               # prints xdogcatCainAbel
  3663.                          print sort @george, 'to', @harry;
  3664.                               # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  3665. ╛KY splice
  3666. ╛DT splice(ARRAY,OFFSET,LENGTH,LIST)
  3667. ╛C splice(ARRAY,OFFSET,LENGTH,LIST)
  3668. splice(ARRAY,OFFSET,LENGTH)
  3669. splice(ARRAY,OFFSET)
  3670.  
  3671.           Removes the elements designated by OFFSET and LENGTH from
  3672.           an array, and replaces them with the elements of LIST, if
  3673.           any.  Returns the elements removed from the array.  The
  3674.           array grows or shrinks as necessary.  If LENGTH is omit-
  3675.           ted, removes everything from OFFSET onward.  The follow-
  3676.           ing equivalencies hold (assuming $[ == 0):
  3677.  
  3678.                          push(@a,$x,$y)                splice(@a,$#a+1,0,$x,$y)
  3679.                          pop(@a)                       splice(@a,-1)
  3680.                          shift(@a)                     splice(@a,0,1)
  3681.                          unshift(@a,$x,$y)             splice(@a,0,0,$x,$y)
  3682.                          $a[$x] = $y                   splice(@a,$x,1,$y);
  3683.  
  3684.           Example, assuming array lengths are passed before arrays:
  3685.  
  3686.                          sub aeq { # compare two array values
  3687.                               local(@a) = splice(@_,0,shift);
  3688.                               local(@b) = splice(@_,0,shift);
  3689.                               return 0 unless @a == @b;     # same len?
  3690.                               while (@a) {
  3691.                                         return 0 if pop(@a) ne pop(@b);
  3692.                               }
  3693.                               return 1;
  3694.                          }
  3695.                          if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
  3696. ╛KY split
  3697. ╛DT split(/PATTERN/,EXPR,LIMIT)
  3698. ╛C split(/PATTERN/,EXPR,LIMIT)
  3699. split(/PATTERN/,EXPR)
  3700. split(/PATTERN/)
  3701. split
  3702.           Splits a string into an array of strings, and returns it.
  3703.           (If not in an array context, returns the number of fields
  3704.           found and splits into the @_ array.  (In an array con-
  3705.           text, you can force the split into @_ by using ?? as the
  3706.           pattern delimiters, but it still returns the array
  3707.           value.)) If EXPR is omitted, splits the $_ string.  If
  3708.           PATTERN is also omitted, splits on whitespace
  3709.           (/[ \t\n]+/).  Anything matching PATTERN is taken to be a
  3710.           delimiter separating the fields.  (Note that the delim-
  3711.           iter may be longer than one character.) If LIMIT is
  3712.           specified, splits into no more than that many fields
  3713.           (though it may split into fewer).  If LIMIT is unspeci-
  3714.           fied, trailing null fields are stripped (which potential
  3715.           users of pop() would do well to remember).  A pattern
  3716.           matching the null string (not to be confused with a null
  3717.           pattern //, which is just one member of the set of pat-
  3718.           terns matching a null string) will split the value of
  3719.           EXPR into separate characters at each point it matches
  3720.           that way.  For example:
  3721.  
  3722.                          print join(':', split(/ */, 'hi there'));
  3723.  
  3724.           produces the output 'h:i:t:h:e:r:e'.
  3725.  
  3726.           The LIMIT parameter can be used to partially split a line
  3727.  
  3728.                          ($login, $passwd, $remainder) = split(/:/, $_, 3);
  3729.  
  3730.           (When assigning to a list, if LIMIT is omitted, perl sup-
  3731.           plies a LIMIT one larger than the number of variables in
  3732.           the list, to avoid unnecessary work.  For the list above
  3733.           LIMIT would have been 4 by default.  In time critical
  3734.           applications it behooves you not to split into more
  3735.           fields than you really need.)
  3736.  
  3737.           If the PATTERN contains parentheses, additional array
  3738.           elements are created from each matching substring in the
  3739.           delimiter.
  3740.  
  3741.                          split(/([,-])/,"1-10,20");
  3742.  
  3743.           produces the array value
  3744.  
  3745.                          (1,'-',10,',',20)
  3746.  
  3747.           The pattern /PATTERN/ may be replaced with an expression
  3748.           to specify patterns that vary at runtime.  (To do runtime
  3749.           compilation only once, use /$variable/o.) As a special
  3750.           case, specifying a space (' ') will split on white space
  3751.           just as split with no arguments does, but leading white
  3752.           space does NOT produce a null first field.  Thus,
  3753.           split(' ') can be used to emulate awk's default behavior,
  3754.           whereas split(/ /) will give you as many null initial
  3755.           fields as there are leading spaces.
  3756.  
  3757.           Example:
  3758.  
  3759.                          open(passwd, '/etc/passwd');
  3760.                          while (<passwd>) {
  3761.                               ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
  3762.                                    = split(/:/);
  3763.                               ...
  3764.                          }
  3765.  
  3766.           (Note that $shell above will still have a newline on it.
  3767.           See chop().) See also join.
  3768. ╛KY sprintf
  3769. ╛DT sprintf(FORMAT,LIST)
  3770. ╛C sprintf(FORMAT,LIST)
  3771.  
  3772.           Returns a string formatted by the usual printf conven-
  3773.           tions.  The * character is not supported.
  3774. ╛KY sqrt
  3775. ╛DT sqrt(EXPR)
  3776. ╛C sqrt(EXPR)
  3777. sqrt EXPR
  3778.  
  3779.           Return the square root of EXPR.  If EXPR is omitted,
  3780.           returns square root of $_.
  3781. ╛KY srand
  3782. ╛DT srand(EXPR)
  3783. ╛C srand(EXPR)
  3784. srand EXPR
  3785.  
  3786.           Sets the random number seed for the rand operator.  If
  3787.           EXPR is omitted, does srand(time).
  3788. ╛KY stat
  3789. ╛DT stat(FILEHANDLE)
  3790. ╛C stat(FILEHANDLE)
  3791. stat FILEHANDLE
  3792. stat(EXPR)
  3793. stat SCALARVARIABLE
  3794.  
  3795.           Returns a 13-element array giving the statistics for a
  3796.           file, either the file opened via FILEHANDLE, or named by
  3797.           EXPR.  Typically used as follows:
  3798.  
  3799.                     ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  3800.                          $atime,$mtime,$ctime,$blksize,$blocks)
  3801.                                    = stat($filename);
  3802.  
  3803.           If stat is passed the special filehandle consisting of an
  3804.           underline, no stat is done, but the current contents of
  3805.           the stat structure from the last stat or filetest are
  3806.           returned.  Example:
  3807.  
  3808.                          if (-x $file && (($d) = stat(_)) && $d < 0) {
  3809.                               print "$file is executable NFS file\n";
  3810.                          }
  3811.           (This only works on machines for which the device number is negative under NFS.)
  3812. ╛KY study
  3813. ╛DT study(SCALAR)
  3814. ╛C study(SCALAR)
  3815. study SCALAR
  3816. study
  3817.           Takes extra time to study SCALAR ($_ if unspecified) in
  3818.           anticipation of doing many pattern matches on the string
  3819.           before it is next modified.  This may or may not save
  3820.           time, depending on the nature and number of patterns you
  3821.           are searching on, and on the distribution of character
  3822.           frequencies in the string to be searched--you probably
  3823.           want to compare runtimes with and without it to see which
  3824.           runs faster.  Those loops which scan for many short con-
  3825.           stant strings (including the constant parts of more com-
  3826.           plex patterns) will benefit most.  You may have only one
  3827.           study active at a time--if you study a different scalar
  3828.           the first is "unstudied".  (The way study works is this:
  3829.           a linked list of every character in the string to be
  3830.           searched is made, so we know, for example, where all the
  3831.           'k' characters are.  From each search string, the rarest
  3832.           character is selected, based on some static frequency
  3833.           tables constructed from some C programs and English text.
  3834.           Only those places that contain this "rarest" character
  3835.           are examined.)
  3836.  
  3837.           For example, here is a loop which inserts index producing
  3838.           entries before any line containing a certain pattern:
  3839.  
  3840.                          while (<>) {
  3841.                               study;
  3842.                               print ".IX foo\n" if /\bfoo\b/;
  3843.                               print ".IX bar\n" if /\bbar\b/;
  3844.                               print ".IX blurfl\n" if /\bblurfl\b/;
  3845.                               ...
  3846.                               print;
  3847.                          }
  3848.  
  3849.           In searching for /\bfoo\b/, only those locations in $_
  3850.           that contain 'f' will be looked at, because 'f' is rarer
  3851.           than 'o'.  In general, this is a big win except in patho-
  3852.           logical cases.  The only question is whether it saves you
  3853.           more time than it took to build the linked list in the
  3854.           first place.
  3855.  
  3856.           Note that if you have to look for strings that you don't
  3857.           know till runtime, you can build an entire loop as a
  3858.           string and eval that to avoid recompiling all your pat-
  3859.           terns all the time.  Together with undefining $/ to input
  3860.           entire files as one record, this can be very fast, often
  3861.           faster than specialized programs like fgrep.  The follow-
  3862.           ing scans a list of files (@files) for a list of words
  3863.           (@words), and prints out the names of those files that
  3864.           contain a match:
  3865.  
  3866.                          $search = 'while (<>) { study;';
  3867.                          foreach $word (@words) {
  3868.                          $search .= "++\$seen{\$ARGV} if /\b$word\b/;\n";
  3869.                          }
  3870.                          $search .= "}";
  3871.                          @ARGV = @files;
  3872.                          undef $/;
  3873.                          eval $search;       # this screams
  3874.                          $/ = "\n";          # put back to normal input delim
  3875.                          foreach $file (sort keys(%seen)) {
  3876.                          print $file, "\n";
  3877.                          }
  3878. ╛KY substr
  3879. ╛DT substr(EXPR,OFFSET,LEN)
  3880. ╛C substr(EXPR,OFFSET,LEN)
  3881. substr(EXPR,OFFSET)
  3882.  
  3883.           Extracts a substring out of EXPR and returns it.  First
  3884.           character is at offset 0, or whatever you've set $[ to.
  3885.           If OFFSET is negative, starts that far from the end of
  3886.           the string.  If LEN is omitted, returns everything to the
  3887.           end of the string.  You can use the substr() function as
  3888.           an lvalue, in which case EXPR must be an lvalue.  If you
  3889.           assign something shorter than LEN, the string will
  3890.           shrink, and if you assign something longer than LEN, the
  3891.           string will grow to accommodate it.  To keep the string
  3892.           the same length you may need to pad or chop your value
  3893.           using sprintf().
  3894. ╛KY symlink
  3895. ╛DT symlink(OLDFILE,NEWFILE)
  3896. ╛C symlink(OLDFILE,NEWFILE)
  3897.  
  3898.           Creates a new filename symbolically linked to the old
  3899.           filename.  Returns 1 for success, 0 otherwise.  On sys-
  3900.           tems that don't support symbolic links, produces a fatal
  3901.           error at run time.  To check for that, use eval:
  3902.  
  3903.                          $symlink_exists = (eval 'symlink("","");', $@ eq '');
  3904. ╛KY syscall
  3905. ╛DT syscall(LIST)
  3906. ╛C syscall(LIST)
  3907. syscall LIST
  3908.  
  3909.           Calls the system call specified as the first element of
  3910.           the list, passing the remaining elements as arguments to
  3911.           the system call.  If unimplemented, produces a fatal
  3912.           error.  The arguments are interpreted as follows: if a
  3913.           given argument is numeric, the argument is passed as an
  3914.           int.  If not, the pointer to the string value is passed.
  3915.           You are responsible to make sure a string is pre-extended
  3916.           long enough to receive any result that might be written
  3917.           into a string.  If your integer arguments are not
  3918.           literals and have never been interpreted in a numeric
  3919.           context, you may need to add 0 to them to force them to
  3920.           look like numbers.
  3921.  
  3922.                          require 'syscall.ph';         # may need to run h2ph
  3923.                          syscall(&SYS_write, fileno(STDOUT), "hi there\n", 9);
  3924. ╛KY sysread
  3925. ╛DT sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3926. ╛C sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3927. sysread(FILEHANDLE,SCALAR,LENGTH)
  3928.  
  3929.           Attempts to read LENGTH bytes of data into variable
  3930.           SCALAR from the specified FILEHANDLE, using the system
  3931.           call read(2).  It bypasses stdio, so mixing this with
  3932.           other kinds of reads may cause confusion.  Returns the
  3933.           number of bytes actually read, or undef if there was an
  3934.           error.  SCALAR will be grown or shrunk to the length
  3935.           actually read.  An OFFSET may be specified to place the
  3936.           read data at some other place than the beginning of the
  3937.           string.
  3938. ╛KY system
  3939. ╛DT system(LIST)
  3940. ╛C system(LIST)
  3941. system LIST
  3942.  
  3943.           Does exactly the same thing as "exec LIST" except that a
  3944.           fork is done first, and the parent process waits for the
  3945.           child process to complete.  Note that argument processing
  3946.           varies depending on the number of arguments.  The return
  3947.           value is the exit status of the program as returned by
  3948.           the wait() call.  To get the actual exit value divide by
  3949.           256.  See also exec.
  3950. ╛KY syswrite
  3951. ╛DT syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3952. ╛C syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3953. syswrite(FILEHANDLE,SCALAR,LENGTH)
  3954.  
  3955.           Attempts to write LENGTH bytes of data from variable
  3956.           SCALAR to the specified FILEHANDLE, using the system call
  3957.           write(2).  It bypasses stdio, so mixing this with prints
  3958.           may cause confusion.  Returns the number of bytes actu-
  3959.           ally written, or undef if there was an error.  An OFFSET
  3960.           may be specified to place the read data at some other
  3961.           place than the beginning of the string.
  3962. ╛KY tell
  3963. ╛DT tell(FILEHANDLE)
  3964. ╛C tell(FILEHANDLE)
  3965. tell FILEHANDLE
  3966. tell
  3967.           Returns the current file position for FILEHANDLE.
  3968.           FILEHANDLE may be an expression whose value gives the
  3969.           name of the actual filehandle.  If FILEHANDLE is omitted,
  3970.           assumes the file last read.
  3971. ╛KY telldir
  3972. ╛DT telldir(DIRHANDLE)
  3973. ╛C telldir(DIRHANDLE)
  3974. telldir DIRHANDLE
  3975.  
  3976.           Returns the current position of the readdir() routines on
  3977.           DIRHANDLE.  Value may be given to seekdir() to access a
  3978.           particular location in a directory.  Has the same caveats
  3979.           about possible directory compaction as the corresponding
  3980.           system library routine.
  3981. ╛KY time
  3982. ╛DT time
  3983. ╛C time
  3984.           Returns the number of non-leap seconds since 00:00:00
  3985.           UTC, January 1, 1970.  Suitable for feeding to gmtime()
  3986.           and localtime().
  3987. ╛KY times
  3988. ╛DT times
  3989. ╛C times
  3990.           Returns a four-element array giving the user and system
  3991.           times, in seconds, for this process and the children of
  3992.           this process.
  3993.  
  3994.                     ($user,$system,$cuser,$csystem) = times;
  3995. ╛KY tr
  3996. ╛DT tr/SEARCHLIST/REPLACEMENTLIST/cds
  3997. ╛C tr/SEARCHLIST/REPLACEMENTLIST/cds
  3998. y/SEARCHLIST/REPLACEMENTLIST/cds
  3999.  
  4000.           Translates all occurrences of the characters found in the
  4001.           search list with the corresponding character in the
  4002.           replacement list.  It returns the number of characters
  4003.           replaced or deleted.  If no string is specified via the
  4004.           =~ or !~ operator, the $_ string is translated.  (The
  4005.           string specified with =~ must be a scalar variable, an
  4006.           array element, or an assignment to one of those, i.e. an
  4007.           lvalue.) For sed devotees, y is provided as a synonym for
  4008.           tr.
  4009.  
  4010.           If the c modifier is specified, the SEARCHLIST character
  4011.           set is complemented.  If the d modifier is specified, any
  4012.           characters specified by SEARCHLIST that are not found in
  4013.           REPLACEMENTLIST are deleted.  (Note that this is slightly
  4014.           more flexible than the behavior of some tr programs,
  4015.           which delete anything they find in the SEARCHLIST,
  4016.           period.) If the s modifier is specified, sequences of
  4017.           characters that were translated to the same character are
  4018.           squashed down to 1 instance of the character.
  4019.  
  4020.           If the d modifier was used, the REPLACEMENTLIST is always
  4021.           interpreted exactly as specified.  Otherwise, if the
  4022.           REPLACEMENTLIST is shorter than the SEARCHLIST, the final
  4023.           character is replicated till it is long enough.  If the
  4024.           REPLACEMENTLIST is null, the SEARCHLIST is replicated.
  4025.           This latter is useful for counting characters in a class,
  4026.           or for squashing character sequences in a class.
  4027.  
  4028.           Examples:
  4029.  
  4030.                     $ARGV[1] =~ y/A-Z/a-z/;   # canonicalize to lower case
  4031.  
  4032.                     $cnt = tr/*/*/;           # count the stars in $_
  4033.  
  4034.                     $cnt = tr/0-9//;          # count the digits in $_
  4035.  
  4036.                     tr/a-zA-Z//s;             # bookkeeper -> bokeper
  4037.  
  4038.                     ($HOST = $host) =~ tr/a-z/A-Z/;
  4039.  
  4040.                     y/a-zA-Z/ /cs;            # change non-alphas to single space
  4041.  
  4042.                     tr/\200-\377/\0-\177/;    # delete 8th bit
  4043. ╛KY truncate
  4044. ╛DT truncate(FILEHANDLE,LENGTH)
  4045. ╛C truncate(FILEHANDLE,LENGTH)
  4046. truncate(EXPR,LENGTH)
  4047.  
  4048.           Truncates the file opened on FILEHANDLE, or named by
  4049.           EXPR, to the specified length.  Produces a fatal error if
  4050.           truncate isn't implemented on your system.
  4051. ╛KY umask
  4052. ╛DT umask(EXPR)
  4053. ╛C umask(EXPR)
  4054. umask EXPR
  4055. umask
  4056.           Sets the umask for the process and returns the old one.
  4057.           If EXPR is omitted, merely returns current umask.
  4058. ╛KY undef
  4059. ╛DT undef(EXPR)
  4060. ╛C undef(EXPR)
  4061. undef EXPR
  4062. undef
  4063.           Undefines the value of EXPR, which must be an lvalue.
  4064.           Use only on a scalar value, an entire array, or a subrou-
  4065.           tine name (using &).  (Undef will probably not do what
  4066.           you expect on most predefined variables or dbm array
  4067.           values.) Always returns the undefined value.  You can
  4068.           omit the EXPR, in which case nothing is undefined, but
  4069.           you still get an undefined value that you could, for
  4070.           instance, return from a subroutine.  Examples:
  4071.  
  4072.                          undef $foo;
  4073.                          undef $bar{'blurfl'};
  4074.                          undef @ary;
  4075.                          undef %assoc;
  4076.                          undef &mysub;
  4077.                          return (wantarray ? () : undef) if $they_blew_it;
  4078. ╛KY unlink
  4079. ╛DT unlink(LIST)
  4080. ╛C unlink(LIST)
  4081. unlink LIST
  4082.  
  4083.           Deletes a list of files.  Returns the number of files
  4084.           successfully deleted.
  4085.  
  4086.                          $cnt = unlink 'a', 'b', 'c';
  4087.                          unlink @goners;
  4088.                          unlink <*.bak>;
  4089.  
  4090.           Note: unlink will not delete directories unless you are
  4091.           superuser and the -U flag is supplied to perl.  Even if
  4092.           these conditions are met, be warned that unlinking a
  4093.           directory can inflict damage on your filesystem.  Use
  4094.           rmdir instead.
  4095. ╛KY unpack
  4096. ╛DT unpack(TEMPLATE,EXPR)
  4097. ╛C unpack(TEMPLATE,EXPR)
  4098.  
  4099.           Unpack does the reverse of pack: it takes a string
  4100.           representing a structure and expands it out into an array
  4101.           value, returning the array value.  (In a scalar context,
  4102.           it merely returns the first value produced.) The TEMPLATE
  4103.           has the same format as in the pack function.  Here's a
  4104.           subroutine that does substring:
  4105.  
  4106.                          sub substr {
  4107.                               local($what,$where,$howmuch) = @_;
  4108.                               unpack("x$where a$howmuch", $what);
  4109.                          }
  4110.  
  4111.           and then there's
  4112.  
  4113.                          sub ord { unpack("c",$_[0]); }
  4114.  
  4115.           In addition, you may prefix a field with a %<number> to
  4116.           indicate that you want a <number>-bit checksum of the
  4117.           items instead of the items themselves.  Default is a 16-
  4118.           bit checksum.  For example, the following computes the
  4119.           same number as the System V sum program:
  4120.  
  4121.                          while (<>) {
  4122.                          $checksum += unpack("%16C*", $_);
  4123.                          }
  4124.                          $checksum %= 65536;
  4125. ╛KY unshift
  4126. ╛DT unshift(ARRAY,LIST)
  4127. ╛C unshift(ARRAY,LIST)
  4128.  
  4129.           Does the opposite of a shift.  Or the opposite of a push,
  4130.           depending on how you look at it.  Prepends list to the
  4131.           front of the array, and returns the number of elements in
  4132.           the new array.
  4133.  
  4134.                          unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/;
  4135. ╛KY utime
  4136. ╛DT utime(LIST)
  4137. ╛C utime(LIST)
  4138. utime LIST
  4139.  
  4140.           Changes the access and modification times on each file of
  4141.           a list of files.  The first two elements of the list must
  4142.           be the NUMERICAL access and modification times, in that
  4143.           order.  Returns the number of files successfully changed.
  4144.           The inode modification time of each file is set to the
  4145.           current time.  Example of a "touch" command:
  4146.  
  4147.                          #!/usr/bin/perl
  4148.                          $now = time;
  4149.                          utime $now, $now, @ARGV;
  4150. ╛KY values
  4151. ╛DT values(ASSOC_ARRAY)
  4152. ╛C values(ASSOC_ARRAY)
  4153. values ASSOC_ARRAY
  4154.  
  4155.           Returns a normal array consisting of all the values of
  4156.           the named associative array.  The values are returned in
  4157.           an apparently random order, but it is the same order as
  4158.           either the keys() or each() function would produce on the
  4159.           same array.  See also keys() and each().
  4160. ╛KY vec
  4161. ╛DT vec(EXPR,OFFSET,BITS)
  4162. ╛C vec(EXPR,OFFSET,BITS)
  4163.  
  4164.           Treats a string as a vector of unsigned integers, and
  4165.           returns the value of the bitfield specified.  May also be
  4166.           assigned to.  BITS must be a power of two from 1 to 32.
  4167.  
  4168.           Vectors created with vec() can also be manipulated with
  4169.           the logical operators |, & and ^, which will assume a bit
  4170.           vector operation is desired when both operands are
  4171.           strings.  This interpretation is not enabled unless there
  4172.           is at least one vec() in your program, to protect older
  4173.           programs.
  4174.  
  4175.           To transform a bit vector into a string or array of 0's
  4176.           and 1's, use these:
  4177.  
  4178.                          $bits = unpack("b*", $vector);
  4179.                          @bits = split(//, unpack("b*", $vector));
  4180.  
  4181.           If you know the exact length in bits, it can be used in
  4182.           place of the *.
  4183. ╛KY wait
  4184. ╛DT wait
  4185. ╛C wait
  4186.           Waits for a child process to terminate and returns the
  4187.           pid of the deceased process, or -1 if there are no child
  4188.           processes.  The status is returned in $?.
  4189. ╛KY waitpid
  4190. ╛DT waitpid(PID,FLAGS)
  4191. ╛C waitpid(PID,FLAGS)
  4192.  
  4193.           Waits for a particular child process to terminate and
  4194.           returns the pid of the deceased process, or -1 if there
  4195.           is no such child process.  The status is returned in $?.
  4196.           If you say
  4197.  
  4198.                          require "sys/wait.h";
  4199.                          ...
  4200.                          waitpid(-1,&WNOHANG);
  4201.  
  4202.           then you can do a non-blocking wait for any process.
  4203.           Non-blocking wait is only available on machines support-
  4204.           ing either the waitpid (2) or wait4 (2) system calls.
  4205.           However, waiting for a particular pid with FLAGS of 0 is
  4206.           implemented everywhere.  (Perl emulates the system call
  4207.           by remembering the status values of processes that have
  4208.           exited but have not been harvested by the Perl script
  4209.           yet.)
  4210. ╛KY wantarray
  4211. ╛DT wantarray
  4212. ╛C wantarray
  4213.  
  4214.           Returns true if the context of the currently executing
  4215.           subroutine is looking for an array value.  Returns false
  4216.           if the context is looking for a scalar.
  4217.  
  4218.                          return wantarray ? () : undef;
  4219. ╛KY warn
  4220. ╛DT warn(LIST)
  4221. ╛C warn(LIST)
  4222. warn LIST
  4223.  
  4224.           Produces a message on STDERR just like "die", but doesn't
  4225.           exit.
  4226. ╛KY write
  4227. ╛DT write(FILEHANDLE)
  4228. ╛C write(FILEHANDLE)
  4229. write(EXPR)
  4230. write
  4231.           Writes a formatted record (possibly multi-line) to the
  4232.           specified file, using the format associated with that
  4233.           file.  By default the format for a file is the one having
  4234.           the same name is the filehandle, but the format for the
  4235.           current output channel (see select) may be set explicitly
  4236.           by assigning the name of the format to the $~ variable.
  4237.  
  4238.           Top of form processing is handled automatically: if there
  4239.           is insufficient room on the current page for the format-
  4240.           ted record, the page is advanced by writing a form feed,
  4241.           a special top-of-page format is used to format the new
  4242.           page header, and then the record is written. By default 
  4243.           the top-of-page format is the name of the filehandle with
  4244.           "_TOP" appended, but it may be dynamicallly set to the
  4245.           format of your choice by assigning the name to the $^ 
  4246.           variable while the filehandle is selected. The number of 
  4247.           lines remaining on the current page is in variable $-, 
  4248.           which can be set to 0 to force a new page.
  4249.  
  4250.           If FILEHANDLE is unspecified, output goes to the current
  4251.           default output channel, which starts out as STDOUT but
  4252.           may be changed by the select operator.  If the FILEHANDLE
  4253.           is an EXPR, then the expression is evaluated and the
  4254.           resulting string is used to look up the name of the
  4255.           FILEHANDLE at run time.  For more on formats, see the
  4256.           section on formats later on.
  4257.  
  4258.           Note that write is NOT the opposite of read.
  4259.  
  4260. ╛KY Perl╔Precedence
  4261. ╛C Perl operators have the following associativity and precedence:
  4262.  
  4263. nonassoc  print printf exec system sort reverse
  4264.                          chmod chown kill unlink utime die return
  4265. left      ,
  4266. right     = += -= *= etc.
  4267. right     ?:
  4268. nonassoc  ..
  4269. left      ||
  4270. left      &&
  4271. left      | ^
  4272. left      &
  4273. nonassoc  == != <=> eq ne cmp
  4274. nonassoc  < > <= >= lt gt le ge
  4275. nonassoc  chdir exit eval reset sleep rand umask
  4276. nonassoc  -r -w -x etc.
  4277. left      << >>
  4278. left      + - .
  4279. left      * / % x
  4280. left      =~ !~
  4281. right     ! ~ and unary minus
  4282. right     **
  4283. nonassoc  ++ --
  4284. left      '('
  4285.  
  4286. As mentioned earlier, if any list operator (print, etc.) or any
  4287. unary operator (chdir, etc.) is followed by a left parenthesis as
  4288. the next token on the same line, the operator and arguments
  4289. within parentheses are taken to be of highest precedence, just
  4290. like a normal function call.  Examples:
  4291.  
  4292.      chdir $foo || die;       # (chdir $foo) || die
  4293.      chdir($foo) || die;      # (chdir $foo) || die
  4294.      chdir ($foo) || die;     # (chdir $foo) || die
  4295.      chdir +($foo) || die;    # (chdir $foo) || die
  4296.  
  4297. but, because * is higher precedence than ||:
  4298.  
  4299.      chdir $foo * 20;         # chdir ($foo * 20)
  4300.      chdir($foo) * 20;        # (chdir $foo) * 20
  4301.      chdir ($foo) * 20;       # (chdir $foo) * 20
  4302.      chdir +($foo) * 20;      # chdir ($foo * 20)
  4303.  
  4304.      rand 10 * 20;            # rand (10 * 20)
  4305.      rand(10) * 20;           # (rand 10) * 20
  4306.      rand (10) * 20;          # (rand 10) * 20
  4307.      rand +(10) * 20;         # rand (10 * 20)
  4308.  
  4309. In the absence of parentheses, the precedence of list operators
  4310. such as print, sort or chmod is either very high or very low
  4311. depending on whether you look at the left side of operator or the
  4312. right side of it.  For example, in
  4313.  
  4314.      @ary = (1, 3, sort 4, 2);
  4315.      print @ary;         # prints 1324
  4316.  
  4317. the commas on the right of the sort are evaluated before the
  4318. sort, but the commas on the left are evaluated after.  In other
  4319. words, list operators tend to gobble up all the arguments that
  4320. follow them, and then act like a simple term with regard to the
  4321. preceding expression.  Note that you have to be careful with
  4322. parens:
  4323.  
  4324.      # These evaluate exit before doing the print:
  4325.      print($foo, exit);  # Obviously not what you want.
  4326.      print $foo, exit;   # Nor is this.
  4327.  
  4328.      # These do the print before evaluating exit:
  4329.      (print $foo), exit; # This is what you want.
  4330.      print($foo), exit;  # Or this.
  4331.      print ($foo), exit; # Or even this.
  4332.  
  4333. Also note that
  4334.  
  4335.      print ($foo & 255) + 1, "\n";
  4336.  
  4337. probably doesn't do what you expect at first glance.
  4338.  
  4339. ╛KY Perl╔Subroutines
  4340. ╛C A subroutine may be declared as follows:
  4341.  
  4342.           sub NAME BLOCK
  4343.  
  4344.  
  4345. Any arguments passed to the routine come in as array @_, that is
  4346. ($_[0], $_[1], ...).  The array @_ is a local array, but its
  4347. values are references to the actual scalar parameters.  The
  4348. return value of the subroutine is the value of the last expres-
  4349. sion evaluated, and can be either an array value or a scalar
  4350. value.  Alternately, a return statement may be used to specify
  4351. the returned value and exit the subroutine.  To create local
  4352. variables see the local operator.
  4353.  
  4354. A subroutine is called using the do operator or the & operator.
  4355.  
  4356. Example:
  4357.  
  4358.      sub MAX {
  4359.                     local($max) = pop(@_);
  4360.                     foreach $foo (@_) {
  4361.                          $max = $foo if $max < $foo;
  4362.                     }
  4363.                     $max;
  4364.      }
  4365.  
  4366.      ...
  4367.      $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
  4368.  
  4369. Example:
  4370.  
  4371.      # get a line, combining continuation lines
  4372.      #  that start with whitespace
  4373.      sub get_line {
  4374.                     $thisline = $lookahead;
  4375.                     line: while ($lookahead = <STDIN>) {
  4376.                          if ($lookahead =~ /^[ \t]/) {
  4377.                               $thisline .= $lookahead;
  4378.                          }
  4379.                          else {
  4380.                               last line;
  4381.                          }
  4382.                     }
  4383.                     $thisline;
  4384.      }
  4385.  
  4386.      $lookahead = <STDIN>;    # get first line
  4387.      while ($_ = do get_line()) {
  4388.                     ...
  4389.      }
  4390.  
  4391. Use array assignment to a local list to name your formal arguments:
  4392.  
  4393.      sub maybeset {
  4394.                     local($key, $value) = @_;
  4395.                     $foo{$key} = $value unless $foo{$key};
  4396.      }
  4397.  
  4398. This also has the effect of turning call-by-reference into call-
  4399. by-value, since the assignment copies the values.
  4400.  
  4401. Subroutines may be called recursively.  If a subroutine is called
  4402. using the & form, the argument list is optional.  If omitted, no
  4403. @_ array is set up for the subroutine; the @_ array at the time
  4404. of the call is visible to subroutine instead.
  4405.  
  4406.      do foo(1,2,3);      # pass three arguments
  4407.      &foo(1,2,3);        # the same
  4408.  
  4409.      do foo();      # pass a null list
  4410.      &foo();             # the same
  4411.      &foo;               # pass no arguments--more efficient
  4412.  
  4413.  
  4414. Passing By Reference
  4415.  
  4416. Sometimes you don't want to pass the value of an array to a sub-
  4417. routine but rather the name of it, so that the subroutine can
  4418. modify the global copy of it rather than working with a local
  4419. copy.  In perl you can refer to all the objects of a particular
  4420. name by prefixing the name with a star: *foo.  When evaluated, it
  4421. produces a scalar value that represents all the objects of that
  4422. name, including any filehandle, format or subroutine.  When
  4423. assigned to within a local() operation, it causes the name men-
  4424. tioned to refer to whatever * value was assigned to it.  Example:
  4425.  
  4426.      sub doubleary {
  4427.                local(*someary) = @_;
  4428.                foreach $elem (@someary) {
  4429.                     $elem *= 2;
  4430.                }
  4431.      }
  4432.      do doubleary(*foo);
  4433.      do doubleary(*bar);
  4434.  
  4435. Assignment to *name is currently recommended only inside a
  4436. local().  You can actually assign to *name anywhere, but the pre-
  4437. vious referent of *name may be stranded forever.  This may or may
  4438. not bother you.
  4439.  
  4440. Note that scalars are already passed by reference, so you can
  4441. modify scalar arguments without using this mechanism by referring
  4442. explicitly to the $_[nnn] in question.  You can modify all the
  4443. elements of an array by passing all the elements as scalars, but
  4444. you have to use the * mechanism to push, pop or change the size
  4445. of an array.  The * mechanism will probably be more efficient in
  4446. any case.
  4447.  
  4448. Since a *name value contains unprintable binary data, if it is
  4449. used as an argument in a print, or as a %s argument in a printf
  4450. or sprintf, it then has the value '*name', just so it prints out
  4451. pretty.
  4452.  
  4453. Even if you don't want to modify an array, this mechanism is use-
  4454. ful for passing multiple arrays in a single LIST, since normally
  4455. the LIST mechanism will merge all the array values so that you
  4456. can't extract out the individual arrays.
  4457.  
  4458. ╛KY Perl╔Regexp
  4459. ╛C Regular Expressions
  4460.  
  4461. The patterns used in pattern matching are regular expressions
  4462. such as those supplied in the Version 8 regexp routines.  (In
  4463. fact, the routines are derived from Henry Spencer's freely redis-
  4464. tributable reimplementation of the V8 routines.) In addition, \w
  4465. matches an alphanumeric character (including "_") and \W a nonal-
  4466. phanumeric.  Word boundaries may be matched by \b, and non-
  4467. boundaries by \B.  A whitespace character is matched by \s, non-
  4468. whitespace by \S.  A numeric character is matched by \d, non-
  4469. numeric by \D.  You may use \w, \s and \d within character
  4470. classes.  Also, \n, \r, \f, \t and \NNN have their normal
  4471. interpretations.  Within character classes \b represents back-
  4472. space rather than a word boundary.  Alternatives may be separated
  4473. by |.  The bracketing construct ( ... ) may also be used, in
  4474. which case \<digit> matches the digit'th substring.  (Outside of
  4475. the pattern, always use $ instead of \ in front of the digit.
  4476. The scope of $<digit> (and $`, $& and $') extends to the end of
  4477. the enclosing BLOCK or eval string, or to the next pattern match
  4478. with subexpressions.  The \<digit> notation sometimes works out-
  4479. side the current pattern, but should not be relied upon.) You may
  4480. have as many parentheses as you wish.  If you have more than 9
  4481. substrings, the variables $10, $11, ... refer to the correspond-
  4482. ing substring.  Within the pattern, \10, \11, etc. refer back to
  4483. substrings if there have been at least that many left parens
  4484. before the backreference.  Otherwise (for backward compatibilty)
  4485. \10 is the same as \010, a backspace, and \11 the same as \011, a
  4486. tab.  And so on.  (\1 through \9 are always backreferences.)
  4487.  
  4488. $+ returns whatever the last bracket match matched.  $& returns
  4489. the entire matched string.  ($0 used to return the same thing,
  4490. but not any more.) $` returns everything before the matched
  4491. string.  $' returns everything after the matched string.  Exam-
  4492. ples:
  4493.  
  4494.      s/^([^ ]*) *([^ ]*)/$2 $1/;   # swap first two words
  4495.      if (/Time: (..):(..):(..)/) {
  4496.                     $hours = $1;
  4497.                     $minutes = $2;
  4498.                     $seconds = $3;
  4499.      }
  4500.  
  4501. By default, the ^ character is only guaranteed to match at the
  4502. beginning of the string, the $ character only at the end (or
  4503. before the newline at the end) and perl does certain optimiza-
  4504. tions with the assumption that the string contains only one line.
  4505. The behavior of ^ and $ on embedded newlines will be incon-
  4506. sistent.  You may, however, wish to treat a string as a multi-
  4507. line buffer, such that the ^ will match after any newline within
  4508. the string, and $ will match before any newline.  At the cost of
  4509. a little more overhead, you can do this by setting the variable
  4510. $* to 1.  Setting it back to 0 makes perl revert to its old
  4511. behavior.
  4512.  
  4513. To facilitate multi-line substitutions, the . character never
  4514. matches a newline (even when $* is 0).  In particular, the fol-
  4515. lowing leaves a newline on the $_ string:
  4516.  
  4517.      $_ = <STDIN>;
  4518.      s/.*(some_string).*/$1/;
  4519.  
  4520. If the newline is unwanted, try one of
  4521.  
  4522.      s/.*(some_string).*\n/$1/;
  4523.      s/.*(some_string)[^\000]*/$1/;
  4524.      s/.*(some_string)(.|\n)*/$1/;
  4525.      chop; s/.*(some_string).*/$1/;
  4526.      /(some_string)/ && ($_ = $1);
  4527.  
  4528. Any item of a regular expression may be followed with digits in
  4529. curly brackets of the form {n,m}, where n gives the minimum
  4530. number of times to match the item and m gives the maximum.  The
  4531. form {n} is equivalent to {n,n} and matches exactly n times.  The
  4532. form {n,} matches n or more times.  (If a curly bracket occurs in
  4533. any other context, it is treated as a regular character.) The *
  4534. modifier is equivalent to {0,}, the + modifier to {1,} and the ?
  4535. modifier to {0,1}.  There is no limit to the size of n or m, but
  4536. large numbers will chew up more memory.
  4537.  
  4538. You will note that all backslashed metacharacters in perl are
  4539. alphanumeric, such as \b, \w, \n.  Unlike some other regular
  4540. expression languages, there are no backslashed symbols that
  4541. aren't alphanumeric.  So anything that looks like \\, \(, \), \<,
  4542. \>, \{, or \} is always interpreted as a literal character, not a
  4543. metacharacter.  This makes it simple to quote a string that you
  4544. want to use for a pattern but that you are afraid might contain
  4545. metacharacters.  Simply quote all the non-alphanumeric charac-
  4546. ters:
  4547.  
  4548.      $pattern =~ s/(\W)/\\$1/g;
  4549. ╛KY Perl╔Formats
  4550. ╛C Output record formats for use with the write operator may
  4551. declared as follows:
  4552.  
  4553.           format NAME =
  4554.           FORMLIST
  4555.           .
  4556.  
  4557. If name is omitted, format "STDOUT" is defined.  FORMLIST con-
  4558. sists of a sequence of lines, each of which may be of one of
  4559. three types:
  4560.  
  4561. 1.  A comment.
  4562.  
  4563. 2.  A "picture" line giving the format for one output line.
  4564.  
  4565. 3.  An argument line supplying values to plug into a picture
  4566.     line.
  4567.  
  4568. Picture lines are printed exactly as they look, except for cer-
  4569. tain fields that substitute values into the line.  Each picture
  4570. field starts with either @ or ^.  The @ field (not to be confused
  4571. with the array marker @) is the normal case; ^ fields are used to
  4572. do rudimentary multi-line text block filling.  The length of the
  4573. field is supplied by padding out the field with multiple <, >, or
  4574. | characters to specify, respectively, left justification, right
  4575. justification, or centering.  As an alternate form of right jus-
  4576. tification, you may also use # characters (with an optional .) to
  4577. specify a numeric field.  (Use of ^ instead of @ causes the field
  4578. to be blanked if undefined.) If any of the values supplied for
  4579. these fields contains a newline, only the text up to the newline
  4580. is printed.  The special field @* can be used for printing
  4581. multi-line values.  It should appear by itself on a line.
  4582.  
  4583. The values are specified on the following line, in the same order
  4584. as the picture fields.  The values should be separated by commas.
  4585.  
  4586. Picture fields that begin with ^ rather than @ are treated spe-
  4587. cially.  The value supplied must be a scalar variable name which
  4588. contains a text string.  Perl puts as much text as it can into
  4589. the field, and then chops off the front of the string so that the
  4590. next time the variable is referenced, more of the text can be
  4591. printed.  Normally you would use a sequence of fields in a verti-
  4592. cal stack to print out a block of text.  If you like, you can end
  4593. the final field with ..., which will appear in the output if the
  4594. text was too long to appear in its entirety.  You can change
  4595. which characters are legal to break on by changing the variable
  4596. $: to a list of the desired characters.
  4597.  
  4598. Since use of ^ fields can produce variable length records if the
  4599. text to be formatted is short, you can suppress blank lines by
  4600. putting the tilde (~) character anywhere in the line.  (Normally
  4601. you should put it in the front if possible, for visibility.) The
  4602. tilde will be translated to a space upon output.  If you put a
  4603. second tilde contiguous to the first, the line will be repeated
  4604. until all the fields on the line are exhausted.  (If you use a
  4605. field of the @ variety, the expression you supply had better not
  4606. give the same value every time forever!)
  4607.  
  4608. Examples:
  4609.  
  4610. # a report on the /etc/passwd file
  4611. format STDOUT_TOP =
  4612.                                         Passwd File
  4613. Name                Login    Office   Uid   Gid Home
  4614. ------------------------------------------------------------------
  4615. .
  4616. format STDOUT =
  4617. @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
  4618. $name,              $login,  $office,$uid,$gid, $home
  4619. .
  4620.  
  4621. # a report from a bug report form
  4622. format STDOUT_TOP =
  4623.                                         Bug Reports
  4624. @<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  4625. $system,                      $%,         $date
  4626. ------------------------------------------------------------------
  4627. .
  4628. format STDOUT =
  4629. Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4630.                $subject
  4631. Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4632.                $index,                       $description
  4633. Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4634.                     $priority,        $date,   $description
  4635. From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4636.           $from,                         $description
  4637. Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4638.                          $programmer,            $description
  4639. ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4640.                                                                  $description
  4641. ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4642.                                                                  $description
  4643. ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4644.                                                                  $description
  4645. ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4646.                                                                  $description
  4647. ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  4648.                                                                  $description
  4649. .
  4650.  
  4651. It is possible to intermix prints with writes on the same output
  4652. channel, but you'll have to handle $- (lines left on the page)
  4653. yourself.
  4654.  
  4655. If you are printing lots of fields that are usually blank, you
  4656. should consider using the reset operator between records.  Not
  4657. only is it more efficient, but it can prevent the bug of adding
  4658. another field and forgetting to zero it.
  4659. ╛KY Perl╔IPC
  4660. ╛C The IPC facilities of perl are built on the Berkeley socket
  4661. mechanism.  If you don't have sockets, you can ignore this sec-
  4662. tion.  The calls have the same names as the corresponding system
  4663. calls, but the arguments tend to differ, for two reasons.  First,
  4664. perl file handles work differently than C file descriptors.
  4665. Second, perl already knows the length of its strings, so you
  4666. don't need to pass that information.  Here is a sample client
  4667. (untested):
  4668.  
  4669.      ($them,$port) = @ARGV;
  4670.      $port = 2345 unless $port;
  4671.      $them = 'localhost' unless $them;
  4672.  
  4673.      $SIG{'INT'} = 'dokill';
  4674.      sub dokill { kill 9,$child if $child; }
  4675.  
  4676.      require 'sys/socket.ph';
  4677.  
  4678.      $sockaddr = 'S n a4 x8';
  4679.      chop($hostname = `hostname`);
  4680.  
  4681.      ($name, $aliases, $proto) = getprotobyname('tcp');
  4682.      ($name, $aliases, $port) = getservbyname($port, 'tcp')
  4683.                     unless $port =~ /^\d+$/;
  4684.      ($name, $aliases, $type, $len, $thisaddr) =
  4685.                                              gethostbyname($hostname);
  4686.      ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
  4687.  
  4688.      $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
  4689.      $that = pack($sockaddr, &AF_INET, $port, $thataddr);
  4690.  
  4691.      socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  4692.      bind(S, $this) || die "bind: $!";
  4693.      connect(S, $that) || die "connect: $!";
  4694.  
  4695.      select(S); $| = 1; select(stdout);
  4696.  
  4697.      if ($child = fork) {
  4698.                     while (<>) {
  4699.                          print S;
  4700.                     }
  4701.                     sleep 3;
  4702.                     do dokill();
  4703.      }
  4704.      else {
  4705.                     while (<S>) {
  4706.                          print;
  4707.  
  4708. And here's a server:
  4709.  
  4710.      ($port) = @ARGV;
  4711.      $port = 2345 unless $port;
  4712.  
  4713.      require 'sys/socket.ph';
  4714.  
  4715.      $sockaddr = 'S n a4 x8';
  4716.  
  4717.      ($name, $aliases, $proto) = getprotobyname('tcp');
  4718.      ($name, $aliases, $port) = getservbyname($port, 'tcp')
  4719.                     unless $port =~ /^\d+$/;
  4720.  
  4721.      $this = pack($sockaddr, &AF_INET, $port, "\0\0\0\0");
  4722.  
  4723.      select(NS); $| = 1; select(stdout);
  4724.  
  4725.      socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  4726.      bind(S, $this) || die "bind: $!";
  4727.      listen(S, 5) || die "connect: $!";
  4728.  
  4729.      select(S); $| = 1; select(stdout);
  4730.  
  4731.      for (;;) {
  4732.                     print "Listening again\n";
  4733.                     ($addr = accept(NS,S)) || die $!;
  4734.                     print "accept ok\n";
  4735.  
  4736.                     ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
  4737.                     @inetaddr = unpack('C4',$inetaddr);
  4738.                     print "$af $port @inetaddr\n";
  4739.  
  4740.                     while (<NS>) {
  4741.                          print;
  4742.                          print NS;
  4743.                     }
  4744.      }
  4745. ╛KY Perl╔Variables
  4746. ╛C The following names have special meaning to perl.  I could have
  4747. used alphabetic symbols for some of these, but I didn't want to
  4748. take the chance that someone would say reset "a-zA-Z" and wipe
  4749. them all out.  You'll just have to suffer along with these silly
  4750. symbols.  Most of them have reasonable mnemonics, or analogues in
  4751. one of the shells.
  4752.  
  4753. $_      The default input and pattern-searching space.  The fol-
  4754.         lowing pairs are equivalent:
  4755.  
  4756.                        while (<>) {...     # only equivalent in while!
  4757.                        while ($_ = <>) {...
  4758.  
  4759.                        /^Subject:/
  4760.                        $_ =~ /^Subject:/
  4761.  
  4762.                        y/a-z/A-Z/
  4763.                        $_ =~ y/a-z/A-Z/
  4764.  
  4765.                        chop
  4766.                        chop($_)
  4767.  
  4768.         (Mnemonic: underline is understood in certain opera-
  4769.         tions.)
  4770.  
  4771. $.      The current input line number of the last filehandle that
  4772.         was read.  Readonly.  Remember that only an explicit
  4773.         close on the filehandle resets the line number.  Since <>
  4774.         never does an explicit close, line numbers increase
  4775.         across ARGV files (but see examples under eof).
  4776.         (Mnemonic: many programs use . to mean the current line
  4777.         number.)
  4778.  
  4779. $/      The input record separator, newline by default.  Works
  4780.         like awk's RS variable, including treating blank lines as
  4781.         delimiters if set to the null string.  You may set it to
  4782.         a multicharacter string to match a multi-character delim-
  4783.         iter.  (Mnemonic: / is used to delimit line boundaries
  4784.         when quoting poetry.)
  4785.  
  4786. $,      The output field separator for the print operator.  Ordi-
  4787.         narily the print operator simply prints out the comma
  4788.         separated fields you specify.  In order to get behavior
  4789.         more like awk, set this variable as you would set awk's
  4790.         OFS variable to specify what is printed between fields.
  4791.         (Mnemonic: what is printed when there is a , in your
  4792.         print statement.)
  4793.  
  4794. $"      This is like $, except that it applies to array values
  4795.         interpolated into a double-quoted string (or similar
  4796.         interpreted string).  Default is a space.  (Mnemonic:
  4797.         obvious, I think.)
  4798.  
  4799. $\      The output record separator for the print operator.
  4800.         Ordinarily the print operator simply prints out the comma
  4801.         separated fields you specify, with no trailing newline or
  4802.         record separator assumed.  In order to get behavior more
  4803.         like awk, set this variable as you would set awk's ORS
  4804.         variable to specify what is printed at the end of the
  4805.         print.  (Mnemonic: you set $\ instead of adding \n at the
  4806.         end of the print.  Also, it's just like /, but it's what
  4807.         you get "back" from perl.)
  4808.  
  4809. $#      The output format for printed numbers.  This variable is
  4810.         a half-hearted attempt to emulate awk's OFMT variable.
  4811.         There are times, however, when awk and perl have differ-
  4812.         ing notions of what is in fact numeric.  Also, the ini-
  4813.         tial value is %.20g rather than %.6g, so you need to set
  4814.         $# explicitly to get awk's value.  (Mnemonic: # is the
  4815.         number sign.)
  4816.  
  4817. $%      The current page number of the currently selected output
  4818.         channel.  (Mnemonic: % is page number in nroff.)
  4819.  
  4820. $=      The current page length (printable lines) of the
  4821.         currently selected output channel.  Default is 60.
  4822.         (Mnemonic: = has horizontal lines.)
  4823.  
  4824. $-      The number of lines left on the page of the currently
  4825.         selected output channel.  (Mnemonic: lines_on_page -
  4826.         lines_printed.)
  4827.  
  4828. $~      The name of the current report format for the currently
  4829.         selected output channel.  (Mnemonic: brother to $^.)
  4830.         Default is name of the filehandle.
  4831.  
  4832. $^      The name of the current top-of-page format for the
  4833.         currently selected output channel.  (Mnemonic: points to
  4834.         top of page.)
  4835.         Default is name of the filehandle with "_TOP" appended.
  4836.  
  4837. $|      If set to nonzero, forces a flush after every write or
  4838.         print on the currently selected output channel.  Default
  4839.         is 0.  Note that STDOUT will typically be line buffered
  4840.         if output is to the terminal and block buffered other-
  4841.         wise.  Setting this variable is useful primarily when you
  4842.         are outputting to a pipe, such as when you are running a
  4843.         perl script under rsh and want to see the output as it's
  4844.         happening.  (Mnemonic: when you want your pipes to be
  4845.         piping hot.)
  4846.  
  4847. $$      The process number of the perl running this script.
  4848.         (Mnemonic: same as shells.)
  4849.  
  4850. $?      The status returned by the last pipe close, backtick (``)
  4851.         command or system operator.  Note that this is the status
  4852.         word returned by the wait() system call, so the exit
  4853.         value of the subprocess is actually ($? >> 8).  $? & 255
  4854.         gives which signal, if any, the process died from, and
  4855.         whether there was a core dump.  (Mnemonic: similar to sh
  4856.         and ksh.)
  4857.  
  4858. $&      The string matched by the last pattern match (not count-
  4859.         ing any matches hidden within a BLOCK or eval enclosed by
  4860.         the current BLOCK).  (Mnemonic: like & in some editors.)
  4861.  
  4862. $`      The string preceding whatever was matched by the last
  4863.         pattern match (not counting any matches hidden within a
  4864.         BLOCK or eval enclosed by the current BLOCK).  (Mnemonic:
  4865.         ` often precedes a quoted string.)
  4866.  
  4867. $'      The string following whatever was matched by the last
  4868.         pattern match (not counting any matches hidden within a
  4869.         BLOCK or eval enclosed by the current BLOCK).  (Mnemonic:
  4870.         ' often follows a quoted string.) Example:
  4871.  
  4872.                          $_ = 'abcdefghi';
  4873.                          /def/;
  4874.                          print "$`:$&:$'\n";      # prints abc:def:ghi
  4875.  
  4876.  
  4877. $+      The last bracket matched by the last search pattern.
  4878.         This is useful if you don't know which of a set of alter-
  4879.         native patterns matched.  For example:
  4880.  
  4881.                   /Version: (.*)|Revision: (.*)/ && ($rev = $+);
  4882.  
  4883.         (Mnemonic: be positive and forward looking.)
  4884.  
  4885. $*      Set to 1 to do multiline matching within a string, 0 to
  4886.         tell perl that it can assume that strings contain a sin-
  4887.         gle line, for the purpose of optimizing pattern matches.
  4888.         Pattern matches on strings containing multiple newlines
  4889.         can produce confusing results when $* is 0.  Default is
  4890.         0.  (Mnemonic: * matches multiple things.) Note that this
  4891.         variable only influences the interpretation of ^ and $.
  4892.         A literal newline can be searched for even when $* == 0.
  4893.  
  4894. $0      Contains the name of the file containing the perl script
  4895.         being executed.  Assigning to $0 modifies the argument
  4896.         area that the ps(1) program sees.  (Mnemonic: same as sh
  4897.         and ksh.)
  4898.  
  4899. $<digit>
  4900.         Contains the subpattern from the corresponding set of
  4901.         parentheses in the last pattern matched, not counting
  4902.         patterns matched in nested blocks that have been exited
  4903.         already.  (Mnemonic: like \digit.)
  4904.  
  4905. $[      The index of the first element in an array, and of the
  4906.         first character in a substring.  Default is 0, but you
  4907.         could set it to 1 to make perl behave more like awk (or
  4908.         Fortran) when subscripting and when evaluating the
  4909.         index() and substr() functions.  (Mnemonic: [ begins sub-
  4910.         scripts.)
  4911.  
  4912. $]      The string printed out when you say "perl -v".  It can be
  4913.         used to determine at the beginning of a script whether
  4914.         the perl interpreter executing the script is in the right
  4915.         range of versions.  If used in a numeric context, returns
  4916.         the version + patchlevel / 1000.  Example:
  4917.  
  4918.                        # see if getc is available
  4919.                             ($version,$patchlevel) =
  4920.                                  $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
  4921.                             print STDERR "(No filename completion available.)\n"
  4922.                                  if $version * 1000 + $patchlevel < 2016;
  4923.  
  4924.         or, used numerically,
  4925.  
  4926.                        warn "No checksumming!\n" if $] < 3.019;
  4927.  
  4928.         (Mnemonic: Is this version of perl in the right bracket?)
  4929.  
  4930. $;      The subscript separator for multi-dimensional array emu-
  4931.         lation.  If you refer to an associative array element as
  4932.                        $foo{$a,$b,$c}
  4933.  
  4934.         it really means
  4935.  
  4936.                        $foo{join($;, $a, $b, $c)}
  4937.  
  4938.         But don't put
  4939.  
  4940.                        @foo{$a,$b,$c}      # a slice--note the @
  4941.  
  4942.         which means
  4943.  
  4944.                        ($foo{$a},$foo{$b},$foo{$c})
  4945.  
  4946.         Default is "\034", the same as SUBSEP in awk.  Note that
  4947.         if your keys contain binary data there might not be any
  4948.         safe value for $;.  (Mnemonic: comma (the syntactic sub-
  4949.         script separator) is a semi-semicolon.  Yeah, I know,
  4950.         it's pretty lame, but $, is already taken for something
  4951.         more important.)
  4952.  
  4953. $!      If used in a numeric context, yields the current value of
  4954.         errno, with all the usual caveats.  (This means that you
  4955.         shouldn't depend on the value of $! to be anything in
  4956.         particular unless you've gotten a specific error return
  4957.         indicating a system error.) If used in a string context,
  4958.         yields the corresponding system error string.  You can
  4959.         assign to $! in order to set errno if, for instance, you
  4960.         want $! to return the string for error n, or you want to
  4961.         set the exit value for the die operator.  (Mnemonic: What
  4962.         just went bang?)
  4963.  
  4964. $@      The perl syntax error message from the last eval command.
  4965.         If null, the last eval parsed and executed correctly
  4966.         (although the operations you invoked may have failed in
  4967.         the normal fashion).  (Mnemonic: Where was the syntax
  4968.         error "at"?)
  4969.  
  4970. $<      The real uid of this process.  (Mnemonic: it's the uid
  4971.         you came FROM, if you're running setuid.)
  4972.  
  4973. $>      The effective uid of this process.  Example:
  4974.  
  4975.                        $< = $>;  # set real uid to the effective uid
  4976.                        ($<,$>) = ($>,$<);  # swap real and effective uid
  4977.  
  4978.         (Mnemonic: it's the uid you went TO, if you're running
  4979.         setuid.) Note: $< and $> can only be swapped on machines
  4980.         supporting setreuid().
  4981.  
  4982. $(      The real gid of this process.  If you are on a machine
  4983.         that supports membership in multiple groups simultane-
  4984.         ously, gives a space separated list of groups you are in.
  4985.         The first number is the one returned by getgid(), and the
  4986.         subsequent ones by getgroups(), one of which may be the
  4987.         same as the first number.  (Mnemonic: parentheses are
  4988.         used to GROUP things.  The real gid is the group you
  4989.         LEFT, if you're running setgid.)
  4990.  
  4991. $)      The effective gid of this process.  If you are on a
  4992.         machine that supports membership in multiple groups
  4993.         simultaneously, gives a space separated list of groups
  4994.         you are in.  The first number is the one returned by
  4995.         getegid(), and the subsequent ones by getgroups(), one of
  4996.         which may be the same as the first number.  (Mnemonic:
  4997.         parentheses are used to GROUP things.  The effective gid
  4998.         is the group that's RIGHT for you, if you're running set-
  4999.         gid.)
  5000.  
  5001.         Note: $<, $>, $( and $) can only be set on machines that
  5002.         support the corresponding set[re][ug]id() routine.  $(
  5003.         and $) can only be swapped on machines supporting setre-
  5004.         gid().
  5005.  
  5006. $:      The current set of characters after which a string may be
  5007.         broken to fill continuation fields (starting with ^) in a
  5008.         format.  Default is " \n-", to break on whitespace or
  5009.         hyphens.  (Mnemonic: a "colon" in poetry is a part of a
  5010.         line.)
  5011.  
  5012. $^D     The current value of the debugging flags.  (Mnemonic:
  5013.         value of -D switch.)
  5014.  
  5015. $^F     The maximum system file descriptor, ordinarily 2.  System 
  5016.         file descriptors are passed to subprocesses, while higher 
  5017.         file descriptors are not. During an open, system file 
  5018.         descriptors are preserved even if the open fails.  Ordinary 
  5019.         file descriptors are closed before the open is attempted.
  5020.  
  5021. $^I     The current value of the inplace-edit extension.  Use
  5022.         undef to disable inplace editing.  (Mnemonic: value of -i
  5023.         switch.)
  5024.  
  5025. $^P     The internal flag that the debugger clears so that it doesn't
  5026.         debug itself.  You could conceivable disable debugging yourself
  5027.         by clearing it.
  5028.         
  5029. $^T     The time at which the script began running, in seconds
  5030.         since the epoch.  The values returned by the -M , -A and
  5031.         -C filetests are based on this value.
  5032.  
  5033. $^W     The current value of the warning switch.  (Mnemonic:
  5034.         related to the -w switch.)
  5035.  
  5036. $^X     The name that Perl itself was invoked as, from argv[0].
  5037.  
  5038. $ARGV   contains the name of the current file when reading from
  5039.         <>.
  5040.  
  5041. @ARGV   The array ARGV contains the command line arguments
  5042.         intended for the script.  Note that $#ARGV is the gen-
  5043.         erally number of arguments minus one, since $ARGV[0] is
  5044.         the first argument, NOT the command name.  See $0 for the
  5045.         command name.
  5046.  
  5047. @INC    The array INC contains the list of places to look for
  5048.         perl scripts to be evaluated by the "do EXPR" command or
  5049.         the "require" command.  It initially consists of the
  5050.         arguments to any -I command line switches, followed by
  5051.         the default perl library, probably "/usr/local/lib/perl",
  5052.         followed by ".", to represent the current directory.
  5053.  
  5054. %INC    The associative array INC contains entries for each
  5055.         filename that has been included via "do" or "require".
  5056.         The key is the filename you specified, and the value is
  5057.         the location of the file actually found.  The "require"
  5058.         command uses this array to determine whether a given file
  5059.         has already been included.
  5060.  
  5061. $ENV{expr}
  5062.         The associative array ENV contains your current environ-
  5063.         ment.  Setting a value in ENV changes the environment for
  5064.         child processes.
  5065.  
  5066. $SIG{expr}
  5067.         The associative array SIG is used to set signal handlers
  5068.         for various signals.  Example:
  5069.  
  5070.                        sub handler {  # 1st argument is signal name
  5071.                             local($sig) = @_;
  5072.                             print "Caught a SIG$sig--shutting down\n";
  5073.                             close(LOG);
  5074.                             exit(0);
  5075.                        }
  5076.  
  5077.                        $SIG{'INT'} = 'handler';
  5078.                        $SIG{'QUIT'} = 'handler';
  5079.                        ...
  5080.                        $SIG{'INT'} = 'DEFAULT'; # restore default action
  5081.                        $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT
  5082.  
  5083.         The SIG array only contains values for the signals actu-
  5084.         ally set within the perl script.
  5085. ╛KY Perl╔Packages
  5086. ╛C Perl provides a mechanism for alternate namespaces to protect
  5087. packages from stomping on each others variables.  By default, a
  5088. perl script starts compiling into the package known as "main".
  5089. By use of the package declaration, you can switch namespaces.
  5090. The scope of the package declaration is from the declaration
  5091. itself to the end of the enclosing block (the same scope as the
  5092. local() operator).  Typically it would be the first declaration
  5093. in a file to be included by the "require" operator.  You can
  5094. switch into a package in more than one place; it merely influ-
  5095. ences which symbol table is used by the compiler for the rest of
  5096. that block.  You can refer to variables and filehandles in other
  5097. packages by prefixing the identifier with the package name and a
  5098. single quote.  If the package name is null, the "main" package as
  5099. assumed.
  5100.  
  5101. Only identifiers starting with letters are stored in the packages
  5102. symbol table.  All other symbols are kept in package "main".  In
  5103. addition, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT,
  5104. ENV, INC and SIG are forced to be in package "main", even when
  5105. used for other purposes than their built-in one.  Note also that,
  5106. if you have a package called "m", "s" or "y", the you can't use
  5107. the qualified form of an identifier since it will be interpreted
  5108. instead as a pattern match, a substitution or a translation.
  5109.  
  5110. Eval'ed strings are compiled in the package in which the eval was
  5111. compiled in.  (Assignments to $SIG{}, however, assume the signal
  5112. handler specified is in the main package.  Qualify the signal
  5113. handler name if you wish to have a signal handler in a package.)
  5114. For an example, examine perldb.pl in the perl library.  It ini-
  5115. tially switches to the DB package so that the debugger doesn't
  5116. interfere with variables in the script you are trying to debug.
  5117. At various points, however, it temporarily switches back to the
  5118. main package to evaluate various expressions in the context of
  5119. the main package.
  5120.  
  5121. The symbol table for a package happens to be stored in the asso-
  5122. ciative array of that name prepended with an underscore.  The
  5123. value in each entry of the associative array is what you are
  5124. referring to when you use the *name notation.  In fact, the fol-
  5125. lowing have the same effect (in package main, anyway), though the
  5126. first is more efficient because it does the symbol table lookups
  5127. at compile time:
  5128.  
  5129.      local(*foo) = *bar;
  5130.      local($_main{'foo'}) = $_main{'bar'};
  5131.  
  5132. You can use this to print out all the variables in a package, for
  5133. instance.  Here is dumpvar.pl from the perl library:
  5134.  
  5135.      package dumpvar;
  5136.  
  5137.      sub main'dumpvar {
  5138.                ($package) = @_;
  5139.                local(*stab) = eval("*_$package");
  5140.                while (($key,$val) = each(%stab)) {
  5141.                          {
  5142.                          local(*entry) = $val;
  5143.                          if (defined $entry) {
  5144.                                    print "\$$key = '$entry'\n";
  5145.                          }
  5146.                          if (defined @entry) {
  5147.                                    print "\@$key = (\n";
  5148.                                    foreach $num ($[ .. $#entry) {
  5149.                                              print "  $num\t'",$entry[$num],"'\n";
  5150.                                    }
  5151.                                    print ")\n";
  5152.                          }
  5153.                          if ($key ne "_$package" && defined %entry) {
  5154.                                    print "\%$key = (\n";
  5155.                                    foreach $key (sort keys(%entry)) {
  5156.                                              print "  $key\t'",$entry{$key},"'\n";
  5157.                                    }
  5158.                                    print ")\n";
  5159.                          }
  5160.                          }
  5161.                }
  5162.      }
  5163.  
  5164. Note that, even though the subroutine is compiled in package
  5165. dumpvar, the name of the subroutine is qualified so that its name
  5166. is inserted into package "main".
  5167. ╛KY Perl╔Style
  5168. ╛C Each programmer will, of course, have his or her own preferences
  5169. in regards to formatting, but there are some general guidelines
  5170. that will make your programs easier to read.
  5171.  
  5172. 1.  Just because you CAN do something a particular way doesn't
  5173.     mean that you SHOULD do it that way.  Perl is designed to
  5174.     give you several ways to do anything, so consider picking the
  5175.     most readable one.  For instance
  5176.  
  5177.          open(FOO,$foo) || die "Can't open $foo: $!";
  5178.  
  5179.     is better than
  5180.  
  5181.          die "Can't open $foo: $!" unless open(FOO,$foo);
  5182.  
  5183.     because the second way hides the main point of the statement
  5184.     in a modifier.  On the other hand
  5185.  
  5186.          print "Starting analysis\n" if $verbose;
  5187.  
  5188.     is better than
  5189.  
  5190.          $verbose && print "Starting analysis\n";
  5191.  
  5192.     since the main point isn't whether the user typed -v or not.
  5193.  
  5194.     Similarly, just because an operator lets you assume default
  5195.     arguments doesn't mean that you have to make use of the
  5196.     defaults.  The defaults are there for lazy systems program-
  5197.     mers writing one-shot programs.  If you want your program to
  5198.     be readable, consider supplying the argument.
  5199.  
  5200.     Along the same lines, just because you can omit parentheses
  5201.     in many places doesn't mean that you ought to:
  5202.  
  5203.          return print reverse sort num values array;
  5204.          return print(reverse(sort num (values(%array))));
  5205.  
  5206.     When in doubt, parenthesize.  At the very least it will let
  5207.     some poor schmuck bounce on the % key in vi.
  5208.  
  5209.     Even if you aren't in doubt, consider the mental welfare of
  5210.     the person who has to maintain the code after you, and who
  5211.     will probably put parens in the wrong place.
  5212.  
  5213. 2.  Don't go through silly contortions to exit a loop at the top
  5214.     or the bottom, when perl provides the "last" operator so you
  5215.     can exit in the middle.  Just outdent it a little to make it
  5216.     more visible:
  5217.  
  5218.     line:
  5219.          for (;;) {
  5220.                    statements;
  5221.          last line if $foo;
  5222.                    next line if /^#/;
  5223.                    statements;
  5224.          }
  5225.  
  5226.  
  5227. 3.  Don't be afraid to use loop labels--they're there to enhance
  5228.     readability as well as to allow multi-level loop breaks.  See
  5229.     last example.
  5230.  
  5231. 4.  For portability, when using features that may not be imple-
  5232.     mented on every machine, test the construct in an eval to see
  5233.     if it fails.  If you know what version or patchlevel a par-
  5234.     ticular feature was implemented, you can test $] to see if it
  5235.     will be there.
  5236.  
  5237. 5.  Choose mnemonic identifiers.
  5238.  
  5239. 6.  Be consistent.
  5240. ╛KY Perl╔Debugging
  5241. ╛C If you invoke perl with a -d switch, your script will be run
  5242. under a debugging monitor.  It will halt before the first execut-
  5243. able statement and ask you for a command, such as:
  5244.  
  5245. h           Prints out a help message.
  5246.  
  5247. T           Stack trace.
  5248.  
  5249. s           Single step.  Executes until it reaches the beginning
  5250.             of another statement.
  5251.  
  5252. n           Next.  Executes over subroutine calls, until it
  5253.             reaches the beginning of the next statement.
  5254.  
  5255. f           Finish.  Executes statements until it has finished
  5256.             the current subroutine.
  5257.  
  5258. c           Continue.  Executes until the next breakpoint is
  5259.             reached.
  5260.  
  5261. c line      Continue to the specified line.  Inserts a one-time-
  5262.             only breakpoint at the specified line.
  5263.  
  5264. <CR>        Repeat last n or s.
  5265.  
  5266. l min+incr  List incr+1 lines starting at min.  If min is omit-
  5267.             ted, starts where last listing left off.  If incr is
  5268.             omitted, previous value of incr is used.
  5269.  
  5270. l min-max   List lines in the indicated range.
  5271.  
  5272. l line      List just the indicated line.
  5273.  
  5274. l           List next window.
  5275.  
  5276. -           List previous window.
  5277.  
  5278. w line      List window around line.
  5279.  
  5280. l subname   List subroutine.  If it's a long subroutine it just
  5281.             lists the beginning.  Use "l" to list more.
  5282.  
  5283. /pattern/   Regular expression search forward for pattern; the
  5284.             final / is optional.
  5285.  
  5286. ?pattern?   Regular expression search backward for pattern; the
  5287.             final ? is optional.
  5288.  
  5289. L           List lines that have breakpoints or actions.
  5290.  
  5291. S           Lists the names of all subroutines.
  5292.  
  5293. t           Toggle trace mode on or off.
  5294.  
  5295. b line condition
  5296.             Set a breakpoint.  If line is omitted, sets a break-
  5297.             point on the line that is about to be executed.  If a
  5298.             condition is specified, it is evaluated each time the
  5299.             statement is reached and a breakpoint is taken only
  5300.             if the condition is true.  Breakpoints may only be
  5301.             set on lines that begin an executable statement.
  5302.  
  5303. b subname condition
  5304.             Set breakpoint at first executable line of subrou-
  5305.             tine.
  5306.  
  5307. d line      Delete breakpoint.  If line is omitted, deletes the
  5308.             breakpoint on the line that is about to be executed.
  5309.  
  5310. D           Delete all breakpoints.
  5311.  
  5312. a line command
  5313.             Set an action for line.  A multi-line command may be
  5314.             entered by backslashing the newlines.
  5315.  
  5316. A           Delete all line actions.
  5317.  
  5318. < command   Set an action to happen before every debugger prompt.
  5319.             A multi-line command may be entered by backslashing
  5320.             the newlines.
  5321.  
  5322. > command   Set an action to happen after the prompt when you've
  5323.             just given a command to return to executing the
  5324.             script.  A multi-line command may be entered by
  5325.             backslashing the newlines.
  5326.  
  5327. V package   List all variables in package.  Default is main pack-
  5328.             age.
  5329.  
  5330. ! number    Redo a debugging command.  If number is omitted,
  5331.             redoes the previous command.
  5332.  
  5333. ! -number   Redo the command that was that many commands ago.
  5334.  
  5335. H -number   Display last n commands.  Only commands longer than
  5336.             one character are listed.  If number is omitted,
  5337.             lists them all.
  5338.  
  5339. q or ^D     Quit.
  5340.  
  5341. command     Execute command as a perl statement.  A missing semi-
  5342.             colon will be supplied.
  5343.  
  5344. p expr      Same as "print DB'OUT expr".  The DB'OUT filehandle
  5345.             is opened to /dev/tty, regardless of where STDOUT may
  5346.             be redirected to.
  5347.  
  5348. If you want to modify the debugger, copy perldb.pl from the perl
  5349. library to your current directory and modify it as necessary.
  5350. (You'll also have to put -I. on your command line.) You can do
  5351. some customization by setting up a .perldb file which contains
  5352. initialization code.  For instance, you could make aliases like
  5353. these:
  5354.  
  5355.           $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
  5356.           $DB'alias{'stop'} = 's/^stop (at|in)/b/';
  5357.           $DB'alias{'.'} =
  5358.           's/^\./p "\$DB\'sub(\$DB\'line):\t",\$DB\'line[\$DB\'line]/';
  5359. ╛PerSetuid
  5360. ╛C Setuid Scripts
  5361.  
  5362. Perl is designed to make it easy to write secure setuid and set-
  5363. gid scripts.  Unlike shells, which are based on multiple substi-
  5364. tution passes on each line of the script, perl uses a more con-
  5365. ventional evaluation scheme with fewer hidden "gotchas".  Addi-
  5366. tionally, since the language has more built-in functionality, it
  5367. has to rely less upon external (and possibly untrustworthy) pro-
  5368. grams to accomplish its purposes.
  5369.  
  5370. In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrin-
  5371. sically insecure, but this kernel feature can be disabled.  If it
  5372. is, perl can emulate the setuid and setgid mechanism when it
  5373. notices the otherwise useless setuid/gid bits on perl scripts.
  5374. If the kernel feature isn't disabled, perl will complain loudly
  5375. that your setuid script is insecure.  You'll need to either dis-
  5376. able the kernel setuid script feature, or put a C wrapper around
  5377. the script.
  5378.  
  5379. When perl is executing a setuid script, it takes special precau-
  5380. tions to prevent you from falling into any obvious traps.  (In
  5381. some ways, a perl script is more secure than the corresponding C
  5382. program.) Any command line argument, environment variable, or
  5383. input is marked as "tainted", and may not be used, directly or
  5384. indirectly, in any command that invokes a subshell, or in any
  5385. command that modifies files, directories or processes.  Any vari-
  5386. able that is set within an expression that has previously refer-
  5387. enced a tainted value also becomes tainted (even if it is logi-
  5388. cally impossible for the tainted value to influence the vari-
  5389. able).  For example:
  5390.  
  5391.      $foo = shift;            # $foo is tainted
  5392.      $bar = $foo,'bar';       # $bar is also tainted
  5393.      $xxx = <>;               # Tainted
  5394.      $path = $ENV{'PATH'};    # Tainted, but see below
  5395.      $abc = 'abc';            # Not tainted
  5396.  
  5397.      system "echo $foo";      # Insecure
  5398.      system "/bin/echo", $foo;     # Secure (doesn't use sh)
  5399.      system "echo $bar";      # Insecure
  5400.      system "echo $abc";      # Insecure until PATH set
  5401.  
  5402.      $ENV{'PATH'} = '/bin:/usr/bin';
  5403.      $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  5404.  
  5405.      $path = $ENV{'PATH'};    # Not tainted
  5406.      system "echo $abc";      # Is secure now!
  5407.  
  5408.      open(FOO,"$foo");        # OK
  5409.      open(FOO,">$foo");       # Not OK
  5410.  
  5411.      open(FOO,"echo $foo|");  # Not OK, but...
  5412.      open(FOO,"-|") || exec 'echo', $foo;    # OK
  5413.  
  5414.      $zzz = `echo $foo`;      # Insecure, zzz tainted
  5415.  
  5416.      unlink $abc,$foo;        # Insecure
  5417.      umask $foo;              # Insecure
  5418.  
  5419.      exec "echo $foo";        # Insecure
  5420.      exec "echo", $foo;       # Secure (doesn't use sh)
  5421.      exec "sh", '-c', $foo;   # Considered secure, alas
  5422.  
  5423. The taintedness is associated with each scalar value, so some
  5424. elements of an array can be tainted, and others not.
  5425.  
  5426. If you try to do something insecure, you will get a fatal error
  5427. saying something like "Insecure dependency" or "Insecure PATH".
  5428. Note that you can still write an insecure system call or exec,
  5429. but only by explicitly doing something like the last example
  5430. above.  You can also bypass the tainting mechanism by referencing
  5431. subpatterns--perl presumes that if you reference a substring
  5432. using $1, $2, etc, you knew what you were doing when you wrote
  5433. the pattern:
  5434.  
  5435.      $ARGV[0] =~ /^-P(\w+)$/;
  5436.      $printer = $1;      # Not tainted
  5437.  
  5438. This is fairly secure since \w+ doesn't match shell metacharac-
  5439. ters.  Use of .+ would have been insecure, but perl doesn't check
  5440. for that, so you must be careful with your patterns.  This is the
  5441. ONLY mechanism for untainting user supplied filenames if you want
  5442. to do file operations on them (unless you make $> equal to $<).
  5443.  
  5444. It's also possible to get into trouble with other operations that
  5445. don't care whether they use tainted values.  Make judicious use
  5446. of the file tests in dealing with any user-supplied filenames.
  5447. When possible, do opens and such after setting $> = $<.  Perl
  5448. doesn't prevent you from opening tainted filenames for reading,
  5449. so be careful what you print out.  The tainting mechanism is
  5450. intended to prevent stupid mistakes, not to remove the need for
  5451. thought.
  5452.  
  5453. ╛KY Perl╔Environment
  5454. ╛C Perl uses PATH in executing subprocesses, and in finding the
  5455. script if -S is used.  HOME or LOGDIR are used if chdir has no
  5456. argument.
  5457.  
  5458. Apart from these, perl uses no environment variables, except to
  5459. make them available to the script being executed, and to child
  5460. processes.  However, scripts running setuid would do well to exe-
  5461. cute the following lines before doing anything else, just to keep
  5462. people honest:
  5463.  
  5464.           $ENV{'PATH'} = '/bin:/usr/bin';    # or whatever you need
  5465.           $ENV{'SHELL'} = '/bin/sh' if $ENV{'SHELL'} ne '';
  5466.           $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  5467. ╛KY Perl╔Diagnostics
  5468. ╛C Compilation errors will tell you the line number of the error,
  5469. with an indication of the next token or token type that was to be
  5470. examined.  (In the case of a script passed to perl via -e
  5471. switches, each -e is counted as one line.)
  5472.  
  5473. Setuid scripts have additional constraints that can produce error
  5474. messages such as "Insecure dependency".  See the section on
  5475. setuid scripts.
  5476.  
  5477. ╛KY Perl╔Traps
  5478. ╛C Accustomed awk users should take special note of the following:
  5479.  
  5480. *   Semicolons are required after all simple statements in perl.
  5481.     Newline is not a statement delimiter.
  5482.  
  5483. *   Curly brackets are required on ifs and whiles.
  5484.  
  5485. *   Variables begin with $ or @ in perl.
  5486.  
  5487. *   Arrays index from 0 unless you set $[.  Likewise string posi-
  5488.     tions in substr() and index().
  5489.  
  5490. *   You have to decide whether your array has numeric or string
  5491.     indices.
  5492.  
  5493. *   Associative array values do not spring into existence upon
  5494.     mere reference.
  5495.  
  5496. *   You have to decide whether you want to use string or numeric
  5497.     comparisons.
  5498.  
  5499. *   Reading an input line does not split it for you.  You get to
  5500.     split it yourself to an array.  And the split operator has
  5501.     different arguments.
  5502.  
  5503. *   The current input line is normally in $_, not $0.  It gen-
  5504.     erally does not have the newline stripped.  ($0 is the name
  5505.     of the program executed.)
  5506.  
  5507. *   $<digit> does not refer to fields--it refers to substrings
  5508.     matched by the last match pattern.
  5509.  
  5510. *   The print statement does not add field and record separators
  5511.     unless you set $, and $\.
  5512.  
  5513. *   You must open your files before you print to them.
  5514.  
  5515. *   The range operator is "..", not comma.  (The comma operator
  5516.     works as in C.)
  5517.  
  5518. *   The match operator is "=~", not "~".  ("~" is the one's com-
  5519.     plement operator, as in C.)
  5520.  
  5521. *   The exponentiation operator is "**", not "^".  ("^" is the
  5522.     XOR operator, as in C.)
  5523.  
  5524. *   The concatenation operator is ".", not the null string.
  5525.     (Using the null string would render "/pat/ /pat/" unparsable,
  5526.     since the third slash would be interpreted as a division
  5527.     operator--the tokener is in fact slightly context sensitive
  5528.     for operators like /, ?, and <.  And in fact, . itself can be
  5529.     the beginning of a number.)
  5530.  
  5531. *   Next, exit and continue work differently.
  5532.  
  5533. *   The following variables work differently
  5534.  
  5535.          Awk               Perl
  5536.          ARGC              $#ARGV
  5537.          ARGV[0]           $0
  5538.          FILENAME          $ARGV
  5539.          FNR               $. - something
  5540.          FS                (whatever you like)
  5541.          NF                $#Fld, or some such
  5542.          NR                $.
  5543.          OFMT              $#
  5544.          OFS               $,
  5545.          ORS               $\
  5546.          RLENGTH           length($&)
  5547.          RS                $/
  5548.          RSTART            length($`)
  5549.          SUBSEP            $;
  5550.  
  5551.  
  5552. *   When in doubt, run the awk construct through a2p and see what
  5553.     it gives you.
  5554.  
  5555. Cerebral C programmers should take note of the following:
  5556.  
  5557. *   Curly brackets are required on ifs and whiles.
  5558.  
  5559. *   You should use "elsif" rather than "else if"
  5560.  
  5561. *   Break and continue become last and next, respectively.
  5562.  
  5563. *   There's no switch statement.
  5564.  
  5565. *   Variables begin with $ or @ in perl.
  5566.  
  5567. *   Printf does not implement *.
  5568.  
  5569. *   Comments begin with #, not /*.
  5570.  
  5571. *   You can't take the address of anything.
  5572.  
  5573. *   ARGV must be capitalized.
  5574.  
  5575. *   The "system" calls link, unlink, rename, etc. return nonzero
  5576.     for success, not 0.
  5577.  
  5578. *   Signal handlers deal with signal names, not numbers.
  5579.  
  5580. Seasoned sed programmers should take note of the following:
  5581.  
  5582. *   Backreferences in substitutions use $ rather than \.
  5583.  
  5584. *   The pattern matching metacharacters (, ), and | do not have
  5585.     backslashes in front.
  5586.  
  5587. *   The range operator is .. rather than comma.
  5588.  
  5589. Sharp shell programmers should take note of the following:
  5590.  
  5591. *   The backtick operator does variable interpretation without
  5592.     regard to the presence of single quotes in the command.
  5593.  
  5594. *   The backtick operator does no translation of the return
  5595.     value, unlike csh.
  5596.  
  5597. *   Shells (especially csh) do several levels of substitution on
  5598.     each command line.  Perl does substitution only in certain
  5599.     constructs such as double quotes, backticks, angle brackets
  5600.     and search patterns.
  5601.  
  5602. *   Shells interpret scripts a little bit at a time.  Perl com-
  5603.     piles the whole program before executing it.
  5604.  
  5605. *   The arguments are available via @ARGV, not $1, $2, etc.
  5606.  
  5607. *   The environment is not automatically made available as vari-
  5608.     ables.
  5609. ╛KY Perl╔Errata
  5610. ╛C The Perl book, Programming Perl, has the following omissions and
  5611. goofs.
  5612.  
  5613. On page 5, the examples which read
  5614.  
  5615.      eval "/usr/bin/perl
  5616.  
  5617. should read
  5618.  
  5619.      eval "exec /usr/bin/perl
  5620.  
  5621.  
  5622. On page 195, the equivalent to the System V sum program only
  5623. works for very small files.  To do larger files, use
  5624.  
  5625.      undef $/;
  5626.      $checksum = unpack("%32C*",<>) % 32767;
  5627.  
  5628. The descriptions of alarm and sleep refer to signal SIGALARM.  
  5629. These should refer to SIGALRM.
  5630.  
  5631. The -0 switch to set the initial value of $/ was added to Perl
  5632. after the book went to press.
  5633.  
  5634. The -l switch now does automatic line ending processing.
  5635.  
  5636. The qx// construct is now a synonym for backticks.
  5637.  
  5638. $0 may now be assigned to set the argument displayed by ps (1).
  5639.  
  5640. The new @###.## format was omitted accidentally from the descrip-
  5641. tion on formats.
  5642.  
  5643. It wasn't known at press time that s///ee caused multiple evalua-
  5644. tions of the replacement expression.  This is to be construed as
  5645. a feature.
  5646.  
  5647. (LIST) x $count now does array replication.
  5648.  
  5649. There is now no limit on the number of parentheses in a regular
  5650. expression.
  5651.  
  5652. In double-quote context, more escapes are supported: \e, \a,
  5653. \x1b, \c[, \l, \L, \u, \U, \E.  The latter five control up/lower
  5654. case translation.
  5655.  
  5656. The $/ variable may now be set to a multi-character delimiter.
  5657.  
  5658. There is now a g modifier on ordinary pattern matching that causes it
  5659. to iterate through a string finding multiple matches.
  5660.  
  5661. All of the $^X variables are new except for $^T.
  5662.  
  5663. The default top-of-form format for FILEHANDLE is now FILEHANDLE_TOP rather
  5664. than top.
  5665.  
  5666. The eval {} and sort {} constructs were added in version 4.018.
  5667.  
  5668. The v and V (little-endian) template options for pack and unpack were
  5669. added in 4.019.
  5670. ╛KY Perl╔Bugs
  5671. ╛C Perl is at the mercy of your machine's definitions of various
  5672. operations such as type casting, atof() and sprintf().
  5673.  
  5674. If your stdio requires an seek or eof between reads and writes on
  5675. a particular stream, so does perl.
  5676.  
  5677. (This doesn't apply to sysread() and syswrite().)
  5678.  
  5679. While none of the built-in data types have any arbitrary size
  5680. limits (apart from memory size), there are still a few arbitrary
  5681. limits: a given identifier may not be longer than 255 characters;
  5682. and no component of your PATH may be longer than 255 if you use -S.
  5683.  
  5684. Perl actually stands for Pathologically Eclectic Rubbish Lister,
  5685. but don't tell anyone I said that.
  5686. ╛KY Perl╔Macintosh╔Extensions
  5687. ╛C The following subroutines are specific to the macintosh version of perl:
  5688.  
  5689. ╛KL answer
  5690. ask
  5691. pick
  5692. sfgetfile
  5693. sfgetfolder
  5694. sfputfile
  5695. ╛KY answer
  5696. ╛DT &answer(PROMPT,BUTTON1,BUTTON2,BUTTON3)
  5697. ╛C &answer(PROMPT)
  5698. &answer(PROMPT,BUTTON1)
  5699. &answer(PROMPT,BUTTON1,BUTTON2)
  5700. &answer(PROMPT,BUTTON1,BUTTON2,BUTTON3)
  5701.  
  5702.           Presents to the user a dialog with 1, 2, or 3 buttons. 
  5703.           
  5704.           Examples:
  5705.           
  5706.           &answer("Nunc et in hora mortis nostrae", "Amen") 
  5707.                               
  5708.                             always returns 0.
  5709.                             
  5710.           &answer("I refuse")
  5711.           
  5712.                               is equivalent to &answer("I refuse", "OK")
  5713.           
  5714.           &answer("Delete hard disk ?", "OK", "Cancel")
  5715.                   
  5716.                             returns 1 for OK, 0 for Cancel
  5717.         
  5718.           &answer("Overwrite existig file", "Overwrite", "Skip", "Cancel")
  5719.               
  5720.                             returns 2 for Overwrite, 1 for Skip, 0 for Cancel
  5721. ╛KY ask
  5722. ╛DT &ask(PROMPT, RESULT, DEFAULT)
  5723. ╛C &ask(PROMPT, RESULT)
  5724. &ask(PROMPT, RESULT, DEFAULT)
  5725.  
  5726.           Asks the user for a string. A default value may be given. Returns 1
  5727.           for OK, 0 for Cancel.
  5728.           
  5729.           Example:
  5730.           
  5731.           &ask("Enter your phone number:", $phone)
  5732.           &ask("Enter your first name", $name, "Bruce")
  5733.           
  5734.                               Useful for Australian database applications
  5735. ╛KY pick
  5736. ╛DT &pick(PROMPT, VALUES, RESULT)
  5737. ╛C &pick(PROMPT, VALUES, RESULT)
  5738.  
  5739.           Asks the user to pick a choice from a list. VALUES is a list of choices. 
  5740.           Returns 1 for OK, 0 for Cancel.
  5741.           
  5742.           Examples:
  5743.           
  5744.           &pick("What's your favorite color baby ?", "Red", "Green", "Gold", $color)
  5745.           &pick("What's your favorite color baby ?", ("Red", "Green", "Gold"), $color)
  5746. ╛KY sfgetfile
  5747. ╛DT &sfgetfile(HPOS, VPOS, TYPELIST, FILE, DEFAULTPATH)
  5748. ╛C &sfgetfile(HPOS, VPOS, TYPELIST, FILE)
  5749. &sfgetfile(HPOS, VPOS, TYPELIST, FILE, DEFAULTPATH)
  5750.  
  5751.           Presents a standard open dialog. TYPELIST is a list of file types.
  5752.           DEFAULTPATH is the folder the dialog is opened to. Returns 1 if 
  5753.           a file was chosen, else 0.
  5754.           
  5755.           Examples:
  5756.           
  5757.           &sfgetfile(75, 75, "TEXT", $file)
  5758.           &sfgetfile(75, 75, "TEXTOBJ MPSY", $file, $ENV{"MPW"})    
  5759. ╛KY sfgetfolder
  5760. ╛DT &sfgetfolder(HPOS, VPOS, FOLDER, DEFAULTPATH)
  5761. ╛C &sfgetfolder(HPOS, VPOS, FOLDER)
  5762. &sfgetfolder(HPOS, VPOS, FOLDER, DEFAULTPATH)
  5763.  
  5764.           Presents a standard open dialog for folders.
  5765.           DEFAULTPATH is the folder the dialog is opened to. Returns 1 if 
  5766.           a folder was chosen, else 0.
  5767.           
  5768.           Examples:
  5769.           
  5770.           &sfgetfolder(75,75,$folder)
  5771.           &sfgetfolder(75,75,$folder,$ENV{"MPW"})
  5772. ╛KY sfputfile
  5773. ╛DT &sfputfile(HPOS, VPOS, PROMPT, FILE, DEFAULTNAME, DEFAULTPATH)
  5774. ╛C &sfputfile(HPOS, VPOS, TYPELIST, FILE)
  5775. &sfputfile(HPOS, VPOS, TYPELIST, FILE, DEFAULTNAME)
  5776. &sfputfile(HPOS, VPOS, TYPELIST, FILE, DEFAULTNAME, DEFAULTPATH)
  5777.  
  5778.           Presents a standard save dialog. DEFAULTNAME is the name of the new 
  5779.           file (defaults to "Untitled"). DEFAULTPATH is the folder the dialog 
  5780.           is opened to. Returns 1 if  a file was chosen, else 0.
  5781.           
  5782.           Examples:
  5783.           
  5784.           &sfputfile(75, 75, "Save as:", $file)
  5785.           &sfputfile(75, 75, "Save as:", $file, "Perl.Scratch", $ENV{"MPW"})    
  5786.